"Declaring a public let for an internal class" - Swift

"Declaring a public let for an internal class" - Swift

我正在尝试制作一个使用 GPS 的应用程序,下面是我的 class GPS 控制器。如果我尝试将其声明为 public,我的经纬度元组会发出编译器警告。

class CoreLocationController : NSObject, CLLocationManagerDelegate {
var locationManager:CLLocationManager = CLLocationManager()
public let ltuple: (latitude:Double, longitude:Double)?;
let location: CLLocation?
override init() {
    super.init()
    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    println("didChangeAuthorizationStatus")
    switch status {

    case .NotDetermined:
        println(".NotDetermined")
        self.locationManager.requestAlwaysAuthorization() //Will use information provided in info.plist
        break

    case .Authorized:
        println(".Authorized")
        self.locationManager.startUpdatingLocation()
        break
    ...

    };
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    //Important things
    let location = locations.last as CLLocation;
    let ltuple = (location.coordinate.latitude, location.coordinate.longitude)
    let geocoder = CLGeocoder()
    //Printing
    let str = "didUpdateLocations:  "+String(format:"%f", location.coordinate.latitude)+String(format:"%f", location.coordinate.longitude);
    println(str)
    println(ltuple)
    }
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error)
}
};

当我试图摆脱第二个 let 时,它给了我 "Cannot assign ltuple to self"。有什么想法吗?

你的class天生就隐含了一个internal class声明,你直接写class SomeClass但是代码真的是internal class SomeClass.

如果您想在 class 中包含 public properties/functions/etc,您必须先将 class 声明为 public

public class SomeClass

public let someImmutableProperty

您可以在 Apple 文档中阅读有关访问控制的所有信息:The Swift Programming Language: Access Control

我个人更喜欢这篇文章,非常简洁,简化了Access Control的概念。

此外,您不应该在 Swift 代码中使用 ;,请参阅此 Swift Style Guide 以供参考。