无法分配给属性“ observationTime”是仅获取属性

时间:2019-05-29 13:51:01

标签: ios swift object getter-setter

尝试将observationTime设置为时间间隔时出现此错误。不确定为什么可以设置属性,我在其他地方设置了

weatherReading?.observationTime = NSTimeIntervalSince1970

@objcMembers class WeatherThirdPartyReadings: NSObject  {

    private var _temperature: Double
    private var _speed: Double
    private var _direction: Double
    private var _observationTime: Double
    private var _isSummaryLoaded: Bool

    var temperature: Double {
        return _temperature
    }
    var speed: Double {
        return _speed
    }
    var direction: Double {
        return _direction
    }
    var observationTime: Double {
        return _observationTime
    }
    var isSummaryLoaded: Bool {
        return _isSummaryLoaded
    }

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self._temperature = temperature
        self._speed = speed
        self._direction = direction
        self._observationTime = observationTime
        self._isSummaryLoaded = isSummaryLoaded
    }
}

2 个答案:

答案 0 :(得分:2)

您需要

var observationTime: Double { 
    set { 
        _observationTime = newValue
    }
    get{ 
        return _observationTime
    }
}

如此

var observationTime: Double {
    return _observationTime
}

使其成为只读属性,get的默认实现是


@objcMembers class WeatherThirdPartyReadings: NSObject  {

    var temperature: Double
    var speed: Double
    var direction: Double
    var observationTime: Double
    var isSummaryLoaded: Bool

    init(temperature: Double, speed: Double, direction: Double, observationTime: Double, isSummaryLoaded: Bool) {
        self.temperature = temperature
        self.speed = speed
        self.direction = direction
        self.observationTime = observationTime
        self.isSummaryLoaded = isSummaryLoaded
    }
}

答案 1 :(得分:1)

问题是,当您使用此语法时,您说的是公共属性仅具有getter,而没有setter可用。您还需要为属性创建设置器。

var observationTime: Double {
    get {
        return _observationTime
    }
    set {
        _observationTime = newValue
    }
}

除非您出于帖子中未指明的其他原因而明确需要支持变量,否则只需声明变量即可,如下所示:

var observationTime: Double