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

Som*_*Guy 0 swift

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

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

    print(thisVariable)
Run Code Online (Sandbox Code Playgroud)

我试图在变量上使用相同的代码,无论其类型如何,但我似乎无法找到干净地执行此操作的方法,因为在if语句中声明的变量不是全局变量.我不能把它变成全局的,因为我不能在if语句之外声明它的类型.有没有一种简单的方法来实现我正在寻找的结果?谢谢!

rma*_*ddy 5

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

let thisVariable: Any
if someVariable {
    thisVariable = 5
} else {
    thisVariable = "This is not a number"
}
Run Code Online (Sandbox Code Playgroud)

甚至:

let thisVariable: Any = someVariable ? 5 : "This is not a number"
Run Code Online (Sandbox Code Playgroud)

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