自定义变量设置器,具有默认值

时间:2016-09-22 11:18:09

标签: swift

我无法为此简单类创建具有默认值的自定义setter。 我想用时区检查实现自定义tz setter。

出了什么问题?

public class City: NSObject {
    public var lat = 0.0, lon = 0.0, name = ""
    private static let def_tz = "GMT+00:00"
    private static let timezones = NSTimeZone.knownTimeZoneNames()
    public var tz: String = def_tz {
        set { //// <<<<< There is the error
            var i = City.timezones.indexOf(newValue ?? City.def_tz) ?? 0
            self.tz = timezones[i].name
        }
        get {
            return self.tz
        }
    }
    // MARK:- Init

    required public init(name: String, lat: Double, lon: Double, tz: String) {
        super.init()
        setup(name, lat: lat, lon: lon, tz: tz)
    }

    private func setup(name: String, lat: Double, lon: Double, tz: String) {
        self.lat = lat
        self.lon = lon

        self.tz = tz == "" ? City.def_tz : tz
        self.name = name
    }

}

错误是

  

City.swift:16:9:使用未解析的标识符&#39;设置&#39;

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

发现这个:

public var lat = 0.0, lon = 0.0, name = ""
private var _tz = def_tz
    private static let def_tz = "GMT+00:00"
    private static let timezones = NSTimeZone.knownTimeZoneNames()
    public var tz: String {
        set {
            let i = City.timezones.indexOf(newValue ?? City.def_tz) ?? 0
            self._tz = City.timezones[i]
        }
        get {
         return self._tz
        }
    }