代码质量

场景3:静态对象的使用

static let nibName = "TableCell"
static let tableViewCellIdentifier = "cellID"

// MARK: 静态对象的使用

override func viewDidLoad() {
    super.viewDidLoad()

    let nib = UINib(nibName: BaseTableViewController.nibName, bundle: nil)
    
    // Required if our subclasses are to use `dequeueReusableCellWithIdentifier(_:forIndexPath:)`.
    tableView.register(nib, forCellReuseIdentifier: BaseTableViewController.tableViewCellIdentifier)
}

场景4:协议扩展

protocol MyProtocal:NSObjectProtocol {
    
    func sayHello()
}

extension MyProtocal where Self:UIView {
    
    func study() -> Void {
        debugPrint("我要学习")
    }
}

class MyView: UIView,MyProtocal {
    
    func sayHello() {
        debugPrint("sayHello")
    }
}

class MyObj: NSObject,MyProtocal {
    
    func sayHello() {
        debugPrint("sayHello")
    }
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        MyView().study()
        MyObj().study()        // 提示错误
    }
}

场景5:willSet 和 didSet

var myValue:String? = nil {
    willSet {
        debugPrint("willSet")
    }
    
    didSet {
        debugPrint("didSet")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    self.myValue = "chenxifanfan"
}
// 控制台输出 :
            willSet
            didSet

场景6:对枚举进行扩展

enum CurStatus {
    case study
    case working
    case speaking
    
    var name:String {
        switch self {
        case .study:return "cc"
        default:return "ff"
        }
    }
}

场景7:无敌的 extension

protocol NameProtocal {
    var name:String { get set }
}

protocol SayProtocal {
    func say()
}

class Person: NSObject {
    
}

extension Person:SayProtocal,NameProtocal {
    
    func say() {
        debugPrint("say")
    }
    
    var name: String {
        get {
            return ""
        }
        set {
            self.name = newValue
        }
    }
}

场景8: 可选协议

protocol StudyProtocal {
    func study()
}

extension StudyProtocal {
    
    func singing() {}
}

class Person: NSObject {
    
}

extension Person:StudyProtocal {
    
    func study() {
        debugPrint("study")
    }
    
    func singing() {
        debugPrint("singing")
    }
}

你可能感兴趣的:(代码质量)