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
}
相关推荐
—Qeyser2 小时前
Flutter CustomScrollView 自定义滚动视图 - 完全指南
android·flutter·ios
—Qeyser3 小时前
Flutter ListView 列表组件完全指南
android·flutter·ios
Swift社区4 小时前
LeetCode 375 - 猜数字大小 II
算法·leetcode·swift
游戏开发爱好者84 小时前
如何在 Windows 环境下测试 iOS App,实时日志,CPU监控
android·ios·小程序·https·uni-app·iphone·webview
ii_best6 小时前
免越狱!按键精灵鹰眼群控让电脑批量掌控 iOS 设备,功能介绍
ios·自动化·电脑
Swift社区1 天前
使用 MetricKit 监控应用性能
ios·swiftui·swift
LawrenceMssss1 天前
由于创建一个完整的App涉及到多个层面(如前端、后端、数据库等),并且每种语言通常有其特定的用途(如Java/Kotlin用于Android开发,Swift/Objective-C用于iOS开发,Py
android·java·ios
2501_915921431 天前
如何在苹果手机上面进行抓包?iOS代理抓包,数据流抓包
android·ios·智能手机·小程序·uni-app·iphone·webview
Boyang_1 天前
在 iOS 26 上@property 的一个小 bug
ios
Swift社区1 天前
LeetCode 374 猜数字大小 - Swift 题解
算法·leetcode·swift