Swift报错:“‘nil‘ is incompatible with return type ‘User‘”

func getUserById(userId: Int) -> User {
    if (userId != nil) {
        ...
    }
    return nil
}

上述代码报了一个错误:“'nil' is incompatible with return type 'User'”,表示“nil”与返回类型“User”不兼容。

解决方案:

将返回值类型改为Optional类型User?

func getUserById(userId: Int) -> User? {
    if (userId != nil) {
        ...
    }
    return nil
}

同理,如果调用getUserById(nil)的时候也会报错:“'nil' is not compatible with expected argument type 'Int'”

将参数类型改为Int?即可

func getUserById(userId: Int?) -> User? {
    if (userId != nil) {
        ...
    }
    return nil
}

猜你喜欢

转载自blog.csdn.net/watson2017/article/details/132756060