无法从不同 class 访问变量

Can't access variable from different class

我正在将我的应用程序更新到 Swift 2.0,但是我 运行 遇到了 CLLocationManager 的问题。

这段代码我已经用了一段时间了,所以我有点疑惑为什么它突然变成了2.0的问题。我正在使用一个全局变量(懒惰,我知道),但它似乎无法在任何其他 class 中访问,除了它被声明的那个。我收到这个错误:

Use of unresolved identifier 'locationManager'

这是我在 class 中声明 locationManager:

的代码
var locationManager = CLLocationManager()

class InitalViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
        if #available(iOS 8.0, *) {
        locationManager.requestAlwaysAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

        if CLLocationManager.locationServicesEnabled() {
            //Requests location use from user for maps
            locationManager.requestWhenInUseAuthorization()
        }
    }
}

这是另一个class中的代码:

@IBAction func centerOnLocation(sender: AnyObject) {
    if locationManager.location != nil {
        let locationCamera = MKMapCamera()
        locationCamera.heading = parkPassed.orientation!
        locationCamera.altitude = 600
        locationCamera.centerCoordinate.latitude = locationManager.location.coordinate.latitude
        locationCamera.centerCoordinate.longitude = locationManager.location.coordinate.longitude

        mapView.setCamera(locationCamera, animated: true)
    }
}

有人有什么想法吗?

全局变量的默认访问级别现在是 internal,就像同一模块中所有源文件的内部访问级别一样。如果 centerOnLocation 在不同的模块中,则需要在全局定义中添加 public 修饰符:

public var locationManager = CLLocationManager() 

您可以实现 CLLocationManager 的扩展以将实例用作单例。

extension CLLocationManager{

  class var sharedManager : CLLocationManager {
    struct Singleton {
      static let instance = CLLocationManager()
    }
    return Singleton.instance
  }
}

然后你就可以在任何class

中访问单例了
@IBAction func centerOnLocation(sender: AnyObject) {
    let locationManager = CLLocationManager.sharedManager
    if locationManager.location != nil {
        let locationCamera = MKMapCamera()
        locationCamera.heading = parkPassed.orientation!
        locationCamera.altitude = 600
        locationCamera.centerCoordinate.latitude = locationManager.location.coordinate.latitude
        locationCamera.centerCoordinate.longitude = locationManager.location.coordinate.longitude

        mapView.setCamera(locationCamera, animated: true)
    }
}