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
}
相关推荐
kkk_皮蛋5 小时前
在移动端使用 WebRTC (Android/iOS)
android·ios·webrtc
Swift社区6 小时前
如何在 SwiftUI 中对 CoreImage 滤镜做实时预览
ios·swiftui·cocoa
ipad协议开发8 小时前
企业微信iPad协议的开发进程
ios·企业微信·ipad
七月巫山晴9 小时前
【iOS】OC中的一些宏
前端·ios·objective-c
初级代码游戏18 小时前
iOS开发 SwiftUI Text的基本用法
ios·swiftui·swift
TheNextByte11 天前
如何安全有效地清除iPad数据以便出售?
安全·ios·ipad
十二测试录1 天前
Android和iOS测试区别
android·经验分享·ios·职场发展·ab测试
张飞签名上架1 天前
深耕全球市场:App上架iOS与Google Play全流程指南
macos·ios·cocoa·ios上架·上架·谷歌上架
Digitally1 天前
iPhone 无法向安卓设备发送图片:轻松解决
android·ios·iphone