gpt4 book ai didi

swift - 转换和检查多种类型的值

转载 作者:行者123 更新时间:2023-11-30 13:50:18 24 4
gpt4 key购买 nike

从下面的代码:

import Foundation

func checkStatus(statusObj: AnyObject) -> String {
if let status = statusObj as? String where status.lowercaseString == "ok" {
return "success"
} else if let status = statusObj as? Int where status >= 200 && status < 300 {
return "success"
} else {
return "failed"
}
}

print(checkStatus("ok"))
print(checkStatus(200))
print(checkStatus("error"))
print(checkStatus(500))

有没有办法将两个成功条件合并到一个语句中?

最佳答案

我最终以这种方式编写,使用 switch 和fallthrough:

func checkStatus(statusObj: AnyObject) -> String {
switch statusObj {
case let status as Int where 200..<300 ~= status:
fallthrough
case "ok" as String:
return "success"
default:
return "failed"
}
}

我必须反转测试,因为在使用 let 的情况下,fallthrough 不起作用。

关于swift - 转换和检查多种类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com