2017-04-13 1 views
0

클래스 내부에서 설정되는 속성을 제한하는 어떤 방법이 있습니까? 문제를 설명하는 코드는 다음과 같습니다.클래스 내부에서 함수 내부에서 거부 속성 편집

import UIKit 

class MyViewController: UIViewController { 
var property: Int? 

func setProperty(_ property: Int?, animated: Bool, 
       withColor color: UIColor, 
       andSomethingElse something: Any) { 
    // only allow property to be set here 
    self.property = property 

    // ... 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // What I'd like to achieve is deny following... 
    property = 42 

    // ...and somehow force to set value exclusively via function 
    setProperty(42, 
       animated: true, 
       withColor: .green, 
       andSomethingElse: LongCat()) 
} 
} 

답변

1

나는 이것을 할 수있는 언어 체계가 있다고 생각하지 않습니다. 다른 클래스에 대해서는 private을 사용하지 않을 수 있습니다.

많은 신경을 쓰면 해당 속성에 대한 래퍼 클래스를 만들 수 있지만 이것이 가치보다 더 번거롭다 고 생각합니다.

일반적으로 _property과 같은 속성을 비공개로 설정하거나 위에 주석을 추가하는 것이 좋습니다.