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
}
相关推荐
CocoaKier10 小时前
神技分享:App加锁,App隐藏?苹果官方自带,只需要一个长按
ios·apple
FungLeo12 小时前
Swift macOS 游戏开发实战|空当接龙 11|使用 Swift Actor 实现自动存档与坏档保护
macos·swift·数据持久化·actor·swift并发
FungLeo16 小时前
Swift macOS 游戏开发实战|空当接龙 09|SwiftUI 与 AppKit 动画,如何分离显示与游戏状态
macos·swiftui·动画·swift·appkit
FungLeo17 小时前
Swift macOS 游戏开发实战|空当接龙 13|SwiftUI 与 AppKit 应用的多语言切换与 RTL 布局
macos·国际化·swiftui·swift·rtl
传奇开心果编程19 小时前
【六大移动UI框架比较学与练】第5课:交互与导航——事件处理、手势与页面路由实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack
Geek-Chow21 小时前
01 · 为什么要在 iOS 上用 Redux
ios
传奇开心果编程2 天前
【六大移动UI框架比较学与练】第3课:文本、图片、布局核心组件实战对照
android·flutter·react native·ios·swiftui·移动开发·android jetpack
FungLeo2 天前
Swift macOS 游戏开发实战|空当接龙 07|使用 Swift 计算稳定牌桌布局与命中区域
macos·swift·游戏开发·界面布局·命中检测
FungLeo2 天前
Swift macOS 游戏开发实战|空当接龙 06|使用 SVG 与 Node.js 制作 macOS 游戏牌面
macos·node.js·svg·swift·游戏素材
艾欧饲2 天前
能力、Entitlement 与扩展:侧载的 App 为什么装上了,有的功能却不能用
ios