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_9159214312 小时前
iOS开发环境搭建详解 Xcode 配置与快蝎轻量级工具选择
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
_瑞13 小时前
试图教会你用 Xcode Instruments
前端·ios·xcode
2501_9159090620 小时前
iOS应用性能监控 Instruments工具与崩溃日志分析完整指南
android·ios·小程序·https·uni-app·iphone·webview
iOS开发上架哦1 天前
Android代码混淆与iOS加固技术详解
后端·ios
2501_915918412 天前
详解iOS App上架至App Store的全流程步骤与注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
库奇噜啦呼2 天前
【iOS】weak底层实现
macos·ios·cocoa
软泡芙2 天前
【IOS】 Swift Package Manager (SPM) 指南
网络·ios·swift
黑化旺仔2 天前
iOS - 计算器仿写
ios
zhaocarbon2 天前
WKWebView 拦截 POST/PUT方法 丢失body的问题解决
ios·xcode·webview
东坡肘子2 天前
不是模型变慢了,是任务变大了 -- 肘子的 Swift 周报 #146
人工智能·swiftui·swift