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
}
相关推荐
wjm0410068 小时前
ios八股文 -- Objective-c
开发语言·ios·objective-c
麦兜*17 小时前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
Digitally1 天前
重置iPhone会删除所有内容吗? 详细回答
ios·iphone
普罗米拉稀1 天前
Flutter 复用艺术:Mixin 与 Abstract 的架构哲学与线性化解密
flutter·ios·面试
kymjs张涛1 天前
零一开源|前沿技术周刊 #12
ios·google·github
2501_915918412 天前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
笔沫拾光2 天前
iOS 正式包签名指南
flutter·ios·ios签名
HarderCoder2 天前
Swift Concurrency:彻底告别“线程思维”,拥抱 Task 的世界
swift
HarderCoder2 天前
深入理解 Swift 中的 async/await:告别回调地狱,拥抱结构化并发
swift
Magnetic_h2 天前
【iOS】锁的原理
笔记·学习·macos·ios·objective-c·cocoa·xcode