2016-09-20 81 views
2

我已經寫了一個在swift 2.2中併發API調用的代碼。當我從swift 2.2更改爲swift 3時,我正面臨着swift語法的問題。幫我出Swift 3轉換

let endPoints = [.email, .others] 
    let fetchGroup = dispatch_group_create() 
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_apply(endPoints.count, queue) { (index) in 
     let enumType = endPoints[index] 
     switch enumType { 
     case .email: 
      //Make email api call 
      break 
     case .others: 
      //Make other api 
      break 
     default: 
      break 
     } 
    } 

    dispatch_group_notify(fetchGroup, dispatch_get_main_queue()) { 
     if endPoints.count > 0 { 
      fail("error") 
     } 
    } 
+0

哪些代碼行特別? –

+0

@ Mr.UB特別是,dispatch_apply和dispatch_group_notify – venky

+0

您似乎沒有使用調度組。所以通知一個小組沒有多大意義。通常在執行一系列異步調用時使用組,但dispatch_apply是同步的,並且在調用本身是異步的例程時通常不會使用它。 – Rob

回答

3

你還記得dispatch_apply()。那麼,它仍然在那裏,並得到一個新的名字。從現在開始,你必須調用concurrentPerform()

let endPoints = [.email, .others] 
    let fetchGroup = DispatchGroup() 
    let queue = DispatchQueue.global (qos : .default) 
    DispatchQueue.concurrentPerform(iterations: endPoints.count) 
    { (index) in 
     let enumType = endPoints[index] 
     switch enumType { 
     case .email: 
      //Make email api call 
      break 
     case .others: 
      //Make other api 
      break 
     default: 
      break 
     } 
    } 
    DispatchGroup().notify(queue: DispatchQueue.main) { 
     if endPoints.count > 0 { 
      fail("error") 
     } 
    } 

更多信息,請參閱this