这是我在 Swift 中的代码行,它调用了一个方法:
networkManager.postUserProfile(self, onSuccess: {(username: String, userID: NSNumber, recommendedLessons: [AnyObject]) -> Void in
... code block
}, onFailure: {(error: NSError) -> Void in
... another code block
})
networkManager
类来自 Objective-C,它是:
- (void)postUserProfile:(Profile *)profile
onSuccess:(void(^)(NSString *username, NSNumber *userID, NSArray *recommendedLessons))successBlock
onFailure:(void(^)(NSError *error))failureBlock;
错误信息是:
error: cannot convert value of type
(String, NSNumber, [AnyObject]) -> Void
to expected argument type((String!, NSNumber!, [AnyObject]!) -> Void)!
当调用一个方法时,我知道 !
运算符将强制解包一个可选的。但是在这种情况下,预期参数类型中的 !
是什么意思?
最佳答案
有许多优秀的现有答案 ( such as these ) 解释了什么是隐式解包选项以及为什么使用它们,所以我不会深入讨论。
Objective-C 头文件中的对象指针类型在 Swift 中被视为隐式展开的可选值,因为编译器不知道 nil 是否是有效值。
如果您在传递给 postUserProfile
的 block 中的每个类型之后添加感叹号,您的代码应该可以编译:
networkManager.postUserProfile(self, onSuccess: { (username: String!, userID: NSNumber!, recommendedLessons: [AnyObject]!) -> Void in
... code block
}, onFailure: { (error: NSError!) -> Void in
... another code block
})
但是,更好的解决方案是添加 nullability annotations到您的 Objective-C 头文件。您标记为可空的属性将是常规可选属性,其余属性将是非可选属性。
关于objective-c - Force unwrapped 在预期的参数类型中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647535/