2017-12-08 3 views
2

私はブロック・モーメントを持っています。 getDataByDatecase .successにデータがあります。それは配列です。その後、その配列をcallAnotherにプッシュし、ループ内の配列の要素を処理する必要があります。すべての要素は、私がmyAnotherMethodに押し込み、completionブロックに私がarrayForDataSourceSaveを作成したいのですが、私のaddが空であるself?.dataSource.save(data: data, add: arrayForDataSourceSaveあるクロージャから別のクロージャへ実際のデータを取得する方法は?

毎回にそれを送りました。これを修正するには?

private func callAnother(data: [AnyModel], completion: @escaping() -> Void) { 
    var arrayForDataSourceSave: []() 
    for element in data { 
     guard let id = element.id else { return } 
     APIService.myAnotherMethod(id: id, completion: { result in 
      switch result { 
      case .success(let well): 
       arrayForDataSourceSave.append(well) 
       print(well) 
      case .error(let error): 
       print("request error: \(error)") 
      } 
     }) 
    } 
    completion() 
} 

func refresh(completion: @escaping() -> Void) { 
    APIService.getDataByDate(date: date, completion: { [weak self] (result) in 
     switch result { 
     case .success(let data): 
      self?.callAnother(data: data, completion: { 
       self?.dataSource.save(data: data, add: arrayForDataSourceSave) 
      }) 
     case .error(let error): 
      print("request error: \(error)") 
     } 
     completion() 
    }) 
} 
+0

あなたは機能をリフレッシュするためにarrayForDataSourceSaveを渡そうとしていますか?私は完了ブロックで配列を渡すことができると思います: "プライベート関数callAnother(データ:[AnyModel]、完了:@エスケープ(結果:[YourArray]) - >())"。成功の呼び出しを完了します。 –

+0

コードがコンパイルをパスしていますか? 'var arrayForDataSourceSave:[]()'構文が間違っているコンストラクタを間違った場所で呼び出すと、構文が正しくありません。var arrayForDataSourceSave:[Any] = [] 'または' var arrayForDataSourceSave = [Any]() ' 'callAnother(data:completion:)'関数のローカル変数であれば 'refresh(completion:)'関数から 'arrayForDataSourceSave'にアクセスしていますか? –

答えて

0

私はDispatchGroupとそのタスクのための意思決定を発見し、私のコードは、良い作品:

private func callAnother(data: [AnyModel]) { 

    let dispatchGroup = DispatchGroup() 
    var arrayForDataSourceSave = [AnyModel]() 

    for element in data { 
     guard let id = element.id else { return } 
     dispatchGroup.enter() 
     APIService.myAnotherMethod(id: id, completion: { result in 
      switch result { 
      case .success(let well): 
       arrayForDataSourceSave.append(well) 
       print(well) 
      case .error(let error): 
       print("request error: \(error)") 
      } 
      dispatchGroup.leave() 
     }) 
    } 

    dispatchGroup.notify(queue: DispatchQueue.main) { 
     self?.dataSource.save(data: data, add: arrayForDataSourceSave) 
    } 
} 

func refresh(completion: @escaping() -> Void) { 
    APIService.getDataByDate(date: date, completion: { [weak self] (result) in 
     switch result { 
     case .success(let data): 
      self?.callAnother(data: data) 
     case .error(let error): 
      print("request error: \(error)") 
     } 
     completion() 
    }) 
} 
関連する問題