Swift
func getUserById(userId: Int) -> User {
if (userId != nil) {
...
}
return nil
}
上述代码报了一个错误:"'nil' is incompatible with return type 'User'",表示"nil"与返回类型"User"不兼容。
解决方案:
将返回值类型改为Optional类型User?
Swift
func getUserById(userId: Int) -> User? {
if (userId != nil) {
...
}
return nil
}
同理,如果调用getUserById(nil)的时候也会报错:"'nil' is not compatible with expected argument type 'Int'"
将参数类型改为Int?即可
Swift
func getUserById(userId: Int?) -> User? {
if (userId != nil) {
...
}
return nil
}