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

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
}
相关推荐
东坡肘子2 天前
Swift 还让你 Excited 吗?-- 肘子的 Swift 周报 #141
人工智能·swiftui·swift
壹方秘境2 天前
我用Go语言开发了一个跨平台的HTTPS抓包和调试工具
前端·后端·ios
sweet丶4 天前
Swift 元编程-Macro
swift
初级代码游戏8 天前
easy Photo Clean公测版:快速清理iPhone照片 邀请公测
ios·iphone
库奇噜啦呼8 天前
【iOS】RunLoop学习
学习·ios
影寂ldy8 天前
WinForm PictureBox控件 + ImageList组件 完整笔记
开发语言·笔记·swift
黑科技iOS上架8 天前
iOS应用周末提交什么情况算卡审
经验分享·ios
zzb15808 天前
ios基础-MVC-UIView
ios·mvc·cocoa
kingbal8 天前
Flutter:Flutter SDK版本管理工具FVM
android·flutter·ios·android-studio·window