Swift stuff

I started with Swift recently. So this is going to be the place I put all the gotchas, tricks and everything including complains
  • Private functions are private:
    This:
    self.addTarget(self, action: Selector("valueChanged"), forControlEvents:.ValueChanged)
    
    private func valueChanged() { ... }
    
    Leads to: unrecognized selector sent to instance the function must not be private.
    func valueChanged() { ... }
    
  • Downcasting:
    These two are basically equal. (cell is an UITableCellView). In objc there is no problem accessing nil stuff. It is a NOP, has good and bad sides. In swift it must be explicitly declared and accessing nils leads to crashes.
    // objc
    [[cell viewWithTag:102] setText:@”Something”];
    
    //or something syntaxly closer to below swift code
    ((UILabel *)[cell viewWithTag:102]).text = @”Something”;
    
    // swift
    (cell.viewWithTag(102) as? UILabel)?.text = “Something”
    
    // to refer `label` more than once create a variable and access its methods if not nil
    if let label = cell.viewWithTag(102) as? UILabel {
        label.text = “Something”
    }
    

This work is licensed under BSD Zero Clause License | nacho4d ®