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
}
相关推荐
zhangkai17 小时前
flutter存储知识点总结
flutter·ios
齐生11 天前
网络知识点 - TCP/IP 四层模型知识大扫盲
笔记·ios
IT技术分享社区1 天前
数码资讯:iPhone 18 Pro,十大升级细节浮出水面
ios·手机·iphone
嵌入式学习菌1 天前
https不校验证书实现及https接口实现
ios·iphone
Swift社区1 天前
LeetCode 391 完美矩形 - Swift 题解
算法·leetcode·swift
忙碌5442 天前
OpenTelemetry实战指南:构建云原生全链路可观测性体系
ios·flink·apache·iphone
升讯威在线客服系统2 天前
从 GC 抖动到稳定低延迟:在升讯威客服系统中实践 Span 与 Memory 的高性能优化
java·javascript·python·算法·性能优化·php·swift