简体   繁体   中英

Cannot assign to property 'observationTime' is a get-only property

I am getting this error when trying to set the observationTime to a time interval. Not sure why I can set a property, ive set it like this in other places

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
    }
}

You need

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

As this

var observationTime: Double {
    return _observationTime
}

makes it a read only property which the3 default implementation of 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
    }
}

The issue is that when you use this syntax you are saying the public property only has a getter and no setter is available. You need to also create the setter for the property.

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

Unless you explicitly need a backing variable for some other reason not indicated in your post, you could simply just declare the variable like so:

var observationTime: Double

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM