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
}
相关推荐
zhensherlock12 小时前
Protocol Launcher 系列:1Writer iOS 上的 Markdown 文档管理
javascript·笔记·ios·typescript·node.js·iphone·ipad
ˇasushiro13 小时前
终端工具配置
开发语言·ios·swift
CDN36014 小时前
iOS/Android 集成游戏盾审核被拒?权限与合规配置修复
android·游戏·ios
sun032215 小时前
旧版Ipad无法访问https的原因(不支持TLS1.3)
ios·https·ipad
Swift社区2 天前
LeetCode 401 二进制手表 - Swift 题解
算法·leetcode·swift
humors2212 天前
[原创]AI工具:读取手机系统文件工具
windows·ios·安卓·鸿蒙·文件·苹果·读取
humors2212 天前
[原创]AI工具:手机文件查杀病毒工具
windows·ios·手机·安卓·鸿蒙·杀毒·苹果
2501_915918412 天前
iOS性能测试工具 Instruments、Keymob的使用方法 不局限 FPS
android·ios·小程序·https·uni-app·iphone·webview
左左右右左右摇晃2 天前
Tasker笔记
ios·iphone
恋猫de小郭2 天前
Android Studio Panda 3 发布,CMP 导致的 Gemini 输入问题
android·ide·flutter·ios·android studio