在if语句之外公开变量

时间:2017-09-19 09:20:49

标签: ios iphone swift3

我试图搞乱Swift代码,我想知道这段代码是做什么的:

if let location = locations.first {
     var locVariable = location.coordinate
}

我知道它得到了坐标,但更简单。该陈述的含义是什么?

因为当我尝试这样做时:

if let location = locations.first {
     var locVariable = location.coordinate
}
print(locVariable)

最后一行会产生错误,说明"使用未解析的标识符' locVariable'"

有没有办法让locVariable全局可用,而不只是在if语句中可用?

对不起,新手在这里。并希望向你们学习。

2 个答案:

答案 0 :(得分:1)

尝试在这种情况下使用guard

guard let location = locations.first else { return }
var locVariable = location.coordinate
print(locVariable)

答案 1 :(得分:1)

这是一个抄袭的小部分 https://andybargh.com/lifetime-scope-and-namespaces-in-swift/ 请阅读整个部分。 我希望它有助于您了解范围的概念。

let three = 3 // global scope
print("Global Scope:")
print(three) // Legal as can see things in the same or enclosing scope.
func outerFunction() {
    print("OuterFunction Scope:")
    var two = 2 // scoped to the braces of the outerFunction
    print(two) // Legal as can see things in the same or enclosing scope.
    print(three) // Also legal as can see things in same or enclosing scope.
    if true {
        print("If Statement Scope:")
        var one = 1 // scoped to the braces of the `if` statement.
        print(one) // Legal as can see things in the same or enclosing scope.
        print(two) // Legal as can see things in same or enclosing scopes.
        print(three) // Also legal for the same reason.
    }
    // print(one) - Would cause an error. Variable `one` is no accessible from outer scope.
}
// print(two) - Would cause an error. Variable `two` is not accessible from outer scope.
相关问题