Swift Protocol Getter and Setter

问题描述 投票:0回答:1

为什么Swift会自动允许开发人员设置属性的值,即使协议仅声明了getter而不是setter。检查以下代码:

import Foundation

protocol Pedometer {
    var pedometerAvailable: Bool { get } 
}

class MockPedometer: Pedometer {
    var pedometerAvailable: Bool = true // even though the Pedometer protocol is only getter I can still set ??
}

let mockPedometer = MockPedometer() 
mockPedometer.pedometerAvailable = false // why I can set the value here 
ios swift
1个回答
0
投票

为什么

因为这是该语言的工作方式。该协议说明采用者必须的行为,而不是采用者不能的行为。 get属性必须具有吸气剂,但没有任何内容说明它也不能具有setter。

(从另一个方向看,get set属性必须同时具有getter和setter;它cannot是只读的,而get属性can是只读的。)

以这种方式思考:采用者必须具有协议规定的属性和功能,但是没有法律说它不能具有任何other属性和功能;那太荒谬了。好,setter实际上是另一个功能。

© www.soinside.com 2019 - 2024. All rights reserved.