只读属性

Read-Only properties

我在 swift 中需要有关 "read-only" 的帮助。我尝试了各种方法,但就是想不出如何正确编译它。这是问题和我的想法。

创建一个名为 isEquilateral 的只读计算 属性 来检查三角形的所有三个边的长度是否相同,returns 如果是则为真,否则为假。

var isEquilateral: Int {

}

如果要 "read-only" 存储 属性,请使用 private(set):

private(set) var isEquilateral = false

如果是从其他属性计算出来的属性,那么,是的,使用computed 属性:

var isEquilateral: Bool {
    return a == b && b == c
}

为了完整起见,而且可能不用说,如果它是一个常量,您只需使用 let:

let isEquilateral = true

struct Triangle {
    let a: Double
    let b: Double
    let c: Double

    let isEquilateral: Bool

    init(a: Double, b: Double, c: Double) {
        self.a = a
        self.b = b
        self.c = c

        isEquilateral = (a == b) && (b == c)
    }
}

是这样的吗? (正如 @vacawama 在评论中所建议的那样)

struct Triangle {
    let edgeA: Int
    let edgeB: Int
    let edgeC: Int

    var isEquilateral: Bool {
        return (edgeA, edgeB) == (edgeB, edgeC)
    }
}

我们来测试一下

let triangle = Triangle(edgeA: 5, edgeB: 5, edgeC: 5)
triangle.isEquilateral // true

let triangle = Triangle(edgeA: 2, edgeB: 2, edgeC: 1)
triangle.isEquilateral // false

A read-only 属性 是 属性,有 getter 但没有 setter。它总是用来return一个值。

class ClassA {
    var one: Int {
        return 1
    }
    var two: Int {
        get { return 2 }
    }
    private(set) var three:Int = 3
    init() {
        one = 1//Cannot assign to property: 'one' is a get-only property
        two = 2//Cannot assign to property: 'two' is a get-only property
        three = 3//allowed to write
        print(one)//allowed to read
        print(two)//allowed to read
        print(three)//allowed to read
    }
}
class ClassB {
    init() {
        var a = ClassA()
        a.one = 1//Cannot assign to property: 'one' is a get-only property
        a.two = 2//Cannot assign to property: 'two' is a get-only property
        a.three = 3//Cannot assign to property: 'three' setter is inaccessible
        print(a.one)//allowed to read
        print(a.two)//allowed to read
        print(a.three)//allowed to read
    }
}