swift /如何在if语句中设置全局变量

时间:2015-08-04 21:59:34

标签: swift global-variables

我有以下代码并且它正在运行。

if passedValue == "location1" {
        var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
        centerMapOnLocation(initialLocation)
        loadInitialData()
        }
if passedValue == "location2" {
        var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
        centerMapOnLocation(initialLocation)
        loadInitialData()
        }

但为了更简洁,我写了这个,但我收到以下错误信息:"使用未解析的标识符'初始位置'"。有什么想法吗?

if passedValue == "location1" {
        var initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
        }
if passedValue == "location2" {
        var initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
        }

centerMapOnLocation(initialLocation)
        loadInitialData()

1 个答案:

答案 0 :(得分:2)

在外面声明var initialLocation: CLLocation!并在里面使用initialLocation

在使用initialLocation之前,您可能还想检查centerMapOnLocation()是否为零。

if initialLocation != nil {
    centerMapOnLocation(initialLocation)
}

说明:centerMapOnLocation()无法查看initialLocation,因为它只存在于if语句中。

完整代码:

var initialLocation: CLLocation!
if passedValue == "location1" {
    initialLocation = CLLocation(latitude: 48.8618, longitude: 2.1539)
}
else if passedValue == "location2" {
    initialLocation = CLLocation(latitude: 52.2398, longitude: 3.3579)
}

if initialLocation != nil {
    centerMapOnLocation(initialLocation)
    loadInitialData()
}