2015-11-16 28 views
1

我有一個函數,即完成後返回一些數組。功能如下:在調用中,無關的參數標籤「完成」,swift 2

func fetchCalendarEvents (completion: (eventArray: [Meeting]) -> Void) -> Void { 

    let eventStore : EKEventStore = EKEventStore() 


    eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { 
     granted, error in 
     if (granted) && (error == nil) { 
      print("access granted: \(granted)") 
      ....... 
     completion (eventArray: arrayOfEvents) 
    } 
     } 
     else { 
      print("error: access not granted \(error)") 
      completion (eventArray: []) 
     } 
    }) 
} 

當試圖這樣調用這個函數,我得到以下錯誤:

//error in this line: Extraneous argument label "completion" in call: 
CalendarController.fetchCalendarEvents(completion:{(eventArray:[Meeting]) -> Void in 
     for meeting in eventArray { 
      print("Meeting: \(meeting.title)") 
     } 
    }) 

我試圖總結我的周圍完成處理的頭,我用這個例子: http://alanduncan.me/2014/06/08/Swift-completion-blocks/ 但是我不明白這段代碼有什麼問題?

此外,當我刪除完成標籤,我得到這個: enter image description here

+0

@matt:不,但你用什麼來代替?我需要抓取日曆事件,你怎麼做(我們支持ios8,ios9,以防萬一) –

+0

對不起,我只是困惑。一大早在這裏! – matt

+0

哈哈,沒有問題:))我想出了一些正確的答案,並對@Eric D.的回答進行了一些調整 –

回答

1

您不能使用data參數標籤,因爲你的說法標籤未命名data而是被命名爲eventArray。在CalendarController.fetchCalendarEvents調用中也有錯誤。

後修復,你的代碼應該是這樣的:

func fetchCalendarEvents (completion: (eventArray: [Meeting]) -> Void) -> Void { 

    let eventStore : EKEventStore = EKEventStore() 

    eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { granted, error in 
     if granted { 
      print("access granted: \(granted)") 
      completion(eventArray: arrayOfEvents) 
     } else { 
      print("error: access not granted \(error)") 
      completion(eventArray: []) 
     } 
    }) 
} 

和:

let calController = CalendarController() 
calController.fetchCalendarEvents { (eventArray) -> Void in 
    // ... 
} 
+2

挑剔:'&& error == nil'永遠不會被達到。如果授予訪問權限,錯誤始終爲零 – vadian

+0

@ vadian同意。我最初決定不干擾OP的代碼邏輯。我想如果我修好它會更好...(完成) – Moritz

+0

@EricD。請在編輯的問題中看到圖像,我修正了數組的名稱,並刪除了無關標籤,仍然出現錯誤 –

0

好,與@Eric D的幫助下,正確的答案是:

let f = CalendarController() 
f.fetchCalendarEvents{(eventArray) -> Void in 
    .... 
} 

問題是我嘗試將方法應用於類,而不是類的類型的變量。我不知道爲什麼,但它只能這樣工作。

相關問題