gpt4 book ai didi

swift - 如何根据 if 语句在 swift 中的结果创建不同类型的变量?

转载 作者:行者123 更新时间:2023-11-28 09:43:22 25 4
gpt4 key购买 nike

我的例子太复杂了,所以这是我想做的一个简化版本:

    if someVariable {
let thisVariable = 5
} else {
let thisVariable = "This is not a number"
}

print(thisVariable)

我试图在一个变量上使用相同的代码,而不管它的类型如何,但我似乎找不到一种方法来干净地做到这一点,因为在 if 语句中声明的变量不是全局的。但是我不能让它成为全局的,因为我不能在 if 语句之外声明它的类型。有没有一种简单的方法可以达到我想要的结果?谢谢!

最佳答案

对于您的简单示例,您可以使用 Any 类型的变量:

let thisVariable: Any
if someVariable {
thisVariable = 5
} else {
thisVariable = "This is not a number"
}

甚至:

let thisVariable: Any = someVariable ? 5 : "This is not a number"

但这可能不是您真实的、更复杂的案例的最佳解决方案。

关于swift - 如何根据 if 语句在 swift 中的结果创建不同类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640414/

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