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
}
相关推荐
专业开发者2 小时前
调试 iOS 蓝牙应用的新方法
物联网·macos·ios·cocoa
1024小神4 小时前
Swift配置WKwebview加载网站或静态资源后,开启调试在电脑上debug
swift
tangbin5830856 小时前
iOS Swift 可选值(Optional)详解
前端·ios
卷心菜加农炮19 小时前
基于Python的FastAPI后端开发框架如何使用PyInstaller 进行打包与部署
ios
北极象1 天前
千问大模型接入示例
ios·iphone·qwen
ipad协议开发1 天前
企业微信 iPad 协议应用机器人开发
ios·企业微信·ipad
kkoral1 天前
基于MS-Swift 为 Qwen3-0.6B-Base 模型搭建可直接调用的 API 服务
python·conda·fastapi·swift
QuantumLeap丶2 天前
《Flutter全栈开发实战指南:从零到高级》- 26 -持续集成与部署
android·flutter·ios
2501_915918412 天前
TCP 抓包分析在复杂网络问题中的作用,从连接和数据流层面理解系统异常行为
网络·网络协议·tcp/ip·ios·小程序·uni-app·iphone
二流小码农2 天前
鸿蒙开发:个人开发者如何使用华为账号登录
android·ios·harmonyos