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
}
相关推荐
2501_9240641131 分钟前
2026年移动应用渗透测试流程方案及iOS与Android框架对比
android·ios
Digitally1 小时前
如何轻松地将数据从 iPhone 传输到 iPhone 17
ios·iphone
2501_916007472 小时前
iOS 自动化上架的工具组合,在多平台环境中实现稳定发布
android·运维·ios·小程序·uni-app·自动化·iphone
TO_ZRG2 小时前
iOS 符号表文件概要
macos·ios·cocoa
shankss17 小时前
GetX 状态管理详解
android·flutter·ios
shankss21 小时前
Flutter 项目启动全流程详解
android·flutter·ios
大熊猫侯佩1 天前
2026 码农漫游:AI 辅助 Swift 代码修复指南
swift·编程语言·apple
大熊猫侯佩1 天前
Swift 6.2 列传(第十五篇):王语嫣的《万剑归宗》与 InlineArray
swift·编程语言·apple
__WanG2 天前
如何申请 Family Controls 权限
ios·swiftui·权限·应用时间管理
杭城小刘3 天前
Weex 底层原理与 APM
ios·前端框架·weex