简体   繁体   中英

Issue calling swift completion handler closure

I have a function which takes a closure as a completion handler. It in turn calls a function that takes one as well. On completion, I want to take the return values from the first completion closure and call the second passing them in.

func saveUserToCloud(user: MBUser, completionHandler: (CKRecord, NSError) -> Void) {
    let userRecord = CKRecord(recordType: kMBUser)
    userRecord.setObject(user.nickname, forKey: kMBUserNickname)
    self.publicDb.saveRecord(userRecord, completionHandler: {record, error in completionHandler(record, error)})
    }
}

This func throws an exception:

fatal error: Can't unwrap Optional.None

func saveUserToCloud(user: MBUser, completionHandler: (CKRecord, NSError) -> Void) {
    let userRecord = CKRecord(recordType: kMBUser)
    userRecord.setObject(user.nickname, forKey: kMBUserNickname)
    // this line throws the exception:
    self.publicDb.saveRecord(userRecord, completionHandler: {record, error in completionHandler(record, error)})
    }
}

What am I doing wrong? I have a record, and no error in this case. I suppose it's trying to unwrap the error?

Thanks

your nickname property is probably an optional property in your MBUser object. You could make it non optional or if you know it's set in this function enforce it with:

userRecord.setObject(user.nickname!, forKey: kMBUserNickname)

If nickname is nil then you will get the error here I don't think the problem is your completionHandler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM