When should I access properties with self in swift?

后端 未结 6 2009
一生所求
一生所求 2020-11-27 04:38

In a simple example like this, I can omit self for referencing backgroundLayer because it\'s unambiguous which backgroundLayer the backgroundColor is set on.



        
6条回答
  •  执笔经年
    2020-11-27 05:30

    As Nick said, in objective-c we had ivars + synthesized properties which gave the _internal variable names to delineate things. Eg.

    @IBOutlet (nonatomic,strong) UITableView *myTableView;
    

    resulting in _myTableView to be (preferably) referenced internally - and self.myTableView to be reference beyond the class. While this is pretty black and white, consider the exception when programmatically instantiating views, you can gain clarity/ simplicity / reduce boilerplate by removing self.

    @interface CustomVC:UIViewController
    {
         UITableView *myTableView; 
    }
    

    In swift, the public / internal properties clarify this scope. If it's a public property that other classes will interact with err on self. Otherwise if it's internal skip self and avoid the automatic repetition. The compiler will catch you when it's needed.

    // UIViewcontroller swift header
    public var title: String? // Localized title for use by a parent controller.
    public var navigationItem: UINavigationItem { get } 
    
    /// In your class
    self.title  = "Clarity"
    self.navigationItem.leftBarButtonItem = UIBarButtonItem()
    
    // In superclass  
     @property(nonatomic, copy) NSString *screenName  // use self.screenName in swift subclass
    
    @IBOutlet myTableView:UITableView  // use self
    public var myTableView:UITableView  // use self
    
    internal var myTableView:UITableView // skip self
    var myTableView:UITableView // skip self 
    

提交回复
热议问题