首页 > 解决方案 > “var simpleDescription: String {get}”中的“get”有什么作用?

问题描述

我在 Apple Swift Tour页面中看到了这个示例。

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

我们可以创建一个符合这个协议的类

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}

我们可以轻松获取和设置属性 simpleDescription 的值。

let a = SimpleClass()
a.simpleDescription = "new description"
print(a.simpleDescription)

get在做什么var simpleDescription: String { get }?我们可以删除它吗?

标签: swift

解决方案


协议的简要背景

实现协议中定义的所有代码的任何类、结构或枚举都被称为符合该协议。协议可以要求任何符合的类型来提供属性(具有特定名称和类型的实例属性或类型属性)。1协议中定义的每个属性(例如var simpleDescription: String在下面的示例中)还必须在类型声明之后(例如String下面示例中的类型)指定它是 gettable{ get }还是 gettable 和 settable { get set }

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

Gettable { get } 与 Gettable 和 Settable 属性 { get set }

通常,可获取和可设置的属性{ get set } 必须是可设置的,这意味着可以编辑/更改属性的值。因此,可获取和可设置的属性不能是常量存储属性(使用let关键字初始化的属性)或只读计算属性。如果协议只要求属性是可获取{ get }的,则任何类型的属性都可以满足该要求,并且如果这对您自己的代码有用,则该属性也可设置是有效的。1

可获取属性与可获取和可设置属性的示例:

// Gettable (var property)

protocol FishSpecies {
    var speciesName: String { get }
}

struct Fish: FishSpecies {
    var height: Int
    var weight: Int
    var speciesName: String
}

var tuna = FishSpecies(speciesName: “Yellowfin”)
print(tuna.speciesName) // returns “Yellowfin”
tuna.speciesName = “Thunnus albacares”
print(tuna.speciesName) // returns “Thunnus albacares”
// Gettable (let 'constant' property)

protocol FishSpecies {
    var speciesName: String { get }
}

struct Fish: FishSpecies {
    var height: Int
    var weight: Int
    let speciesName: String
}

let tuna = FishSpecies(fishName: “Yellowfin”)
print(tuna.speciesName) // returns “Yellowfin”
// Gettable and Settable (Constant Property)

protocol FullyNamed {
    var fullName: String { get set }
}

struct Golfer: FullyNamed {
    let fullName: String
}

let baller = Golfer(fullName: “Collin Morikawa”)
// -> Error message: Type ‘Golfer’ does not conform to protocol ‘FullyNamed’
// Gettable and Settable properties cannot be constant stored properties
// Gettable and Settable (Computed Property)

protocol FullyNamed {
    var fullName: String { get }
}

struct Golfer: FullyNamed {
    fileprivate var name: String
    var fullName: String {
        get {
            return name
        }
        set {
            name = newValue
        }
    }
}

var bigCat = Golfer(name: "Woods")
print(bigCat.fullName) // returns "Woods"
bigCat.fullName = "Tiger Woods"
print(bigCat.fullName) // returns "Tiger Woods"

参考资料/延伸阅读

  1. Apple 的 Swift协议文档:属性要求
  2. Apple 的 Swift属性文档

推荐阅读