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
}
相关推荐
与火星的孩子对话8 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
恋猫de小郭1 天前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
点金石游戏出海2 天前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道
旷世奇才李先生2 天前
Swift 安装使用教程
开发语言·ios·swift
90后的晨仔2 天前
Xcode16报错: SDK does not contain 'libarclite' at the path '/Applicati
ios
finger244802 天前
谈一谈iOS线程管理
ios·objective-c
Digitally2 天前
如何将大型视频文件从 iPhone 传输到 PC
ios·iphone
梅名智2 天前
IOS 蓝牙连接
macos·ios·cocoa
美狐美颜sdk2 天前
跨平台直播美颜SDK集成实录:Android/iOS如何适配贴纸功能
android·人工智能·ios·架构·音视频·美颜sdk·第三方美颜sdk
恋猫de小郭2 天前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin