반응형
protocol SampleProtocol {
var x: Int { get }
}
struct SampleStruct: SampleProtocol {
var x: Int
}
var sample: SampleStruct = SampleStruct(x: 10)
sample.x = 20
print(sample.x) // prints 20
프로토콜내에서 get, set을 설정해주는 경우
sample 변수가 SampleStruct타입이 되면
protocol의 x가 read-only 임에도 불구하고 x값이 변환이된다.
어노테이션을 해주지 않아 타입추정을 하게되는 등,
타입이 SampleStruct가 되면 Struct를 생성하기 때문에 별 관계없는 상태가 된다.
protocol SampleProtocol {
var x: Int { get }
}
struct SampleStruct: SampleProtocol {
var x: Int
}
var sample: SampleProtocol = SampleStruct(x: 10)
sample.x = 20 // *Error: Cannot assign to property: 'x' is a get-only property
print(sample.x)
위처럼 Protocol로 타입을 받아주면 의도했던대로 오류가 난다.
반응형
'iOS > Swift' 카테고리의 다른 글
[Swift] 동시성, 병렬성, 동기, 비동기 (1) | 2024.02.01 |
---|---|
[Memory] heap memory (0) | 2024.02.01 |
[Trouble] stride(from: to: by:) 와 stride(from: through: by:) (0) | 2023.04.07 |
[Swift] Timer 사용방법, 주의사항 (0) | 2023.03.22 |