Objective c force unwrapped在预期的参数类型中是什么意思?
这是我在Swift中的代码行,它调用一个方法:Objective c force unwrapped在预期的参数类型中是什么意思?,objective-c,xcode,swift,Objective C,Xcode,Swift,这是我在Swift中的代码行,它调用一个方法: networkManager.postUserProfile(self, onSuccess: {(username: String, userID: NSNumber, recommendedLessons: [AnyObject]) -> Void in ... code block }, onFailure: {(error: NSError) -> Void in ... another code block }
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;
错误消息是:
错误:无法将类型为(String,NSNumber,[AnyObject])->Void的值转换为预期的参数类型((String!,NSNumber!,[AnyObject]!)->Void)代码>
调用方法时,我知道代码>操作员将强制展开一个可选文件。但是在这种情况下,的含义是什么
在预期的参数类型中?有许多优秀的现有答案()解释了隐式展开选项是什么以及为什么使用它们,所以我将不深入讨论
Objective-C头文件中的对象指针类型在Swift中被视为隐式展开的选项,因为编译器不知道nil是否为有效值
如果在要传递到posterprofile
的块中的每个类型后面添加感叹号,则代码应该编译:
networkManager.postUserProfile(self, onSuccess: { (username: String!, userID: NSNumber!, recommendedLessons: [AnyObject]!) -> Void in
... code block
}, onFailure: { (error: NSError!) -> Void in
... another code block
})
但是,更好的解决方案是添加到Objective-C头文件中。标记为nullable的属性将是常规的可选属性,其余的将是非可选属性。FYI当然,在调用函数中添加感叹号和括号并不能解决问题。谢谢!可空性注释将使这变得容易得多。