Swift之协议(Protocols)

// 如果你为doesNotNeedToBeSettable只读属性实现了setter,也不会报错

protocol SomeProtocol {

    var musBeSettable: Int { get set }

    var doesNotNeedToBeSettable: Int { get }

    

}


protocol AnotherProtocol {

    class var someTypeProperty: Int { get set }

    

}


protocol FullyNamed {

    var fullName: String { get }

}



//遵守协议者,必须要有一个fullName的属性

struct Person: FullyNamed {

    var fullName: String

}


var john = Person(fullName: "John Appleseed")

// FullyNamed协议的属性现实为计算属性

class Startship: FullyNamed {

    var prefix: String?

    var name: String

    init(name: String, prefix: String? = nil) {

        self.name = name

        self.prefix = prefix

        

    }

    var fullName: String {

        return (prefix != nil ? prefix! + " " : " ") + name

    }

}


var ncc1701 = Startship(name: "Enterprise", prefix: "USS")

ncc1701.fullName   // "USS Enterprise"


你可能感兴趣的:(Swift,swift,iOS)