How can I bind promises in Swift inside a loop?

I am building a Swift-based iOS application that uses PromiseKit to handle promises (although I am open to switching if this makes it easier to solve my problem). There is a section of code designed to handle file rewriting issues.

I have some code that looks something like this:

let fileList = [list, of, files, could, be, any, length, ...]

for file in fileList {
  if(fileAlreadyExists) {
    let overwrite = Promise<Bool> { fulfill, reject in
      let alert = UIAlertController(message: "Overwrite the file?")
      alert.addAction(UIAlertAction(title: "Yes", handler: { action in 
        fulfill(true)
      }
      alert.addAction(UIAlertAction(title: "No", handler: { action in 
        fulfill(false)
      }
    } else {
      fulfill(true)
    }
  }

  overwrite.then { result -> Promise<Void> in
    Promise<Void> { fulfill, reject in
      if(result) {
        // Overwrite the file
      } else {
        // Don't overwrite the file
      }
  }
}

; "" , , , , UIAlertController , . , promises , , "" "" ( "" " " ), for . , , .

promises, ? , - .

: . , , Swift ( iOS), . , , , .

+4
1

: , . then. :

function promptOverwrite(objects) {
    if (objects is empty)
        return
    let overwrite = [...]  // same as your code
    overwrite.then {
        do positive or negative action
        // Recur on the rest of the objects
        promptOverwrite(objects[1:])
    }
}

, , promises. (, promises , ).

, then -happens , - , . , , , .

, promises, , -, , () . , promises. , -

function promptOverwrite(objects) {
    spawn an NSThread with target _promptOverwriteInternal(objects)
}
function _promptOverwriteInternal(objects) {
    for obj in objects {
        let overwrite = [...]  // same as your code
        overwrite.then(...)    // same as your code
        overwrite.awaitCompletion()
    }
}

promises , :

function _promptOverwriteInternal(objects) {
    semaphore = createSemaphore(0)
    for obj in objects {
        let overwrite = [...]  // same as your code
        overwrite.then(...)    // same as your code
        overwrite.always {
            semaphore.release(1)
        }
        semaphore.acquire(1)  // wait for completion
    }
}
0

All Articles