只读属性

All*_*ems 30 readonly swift

我需要swift中的"只读"帮助.我尝试了各种方法,但根本无法弄清楚如何编译它没有错误.这是问题和我的想法.

创建一个名为isEquilateral的只读计算属性,它检查三角形的所有三边是否都是相同的长度,如果是,则返回true,如果不是则返回false.

var isEquilateral: Int {

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 98

如果您想要"只读"存储属性,请使用private(set):

private(set) var isEquilateral = false
Run Code Online (Sandbox Code Playgroud)

如果它是从其他属性计算的属性,则是,使用computed属性:

var isEquilateral: Bool {
    return a == b && b == c
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*tti 17

像这样的东西?(正如@vacawama在评论中所建议的那样)

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

    var isEquilateral: Bool {
        return (edgeA, edgeB) == (edgeB, edgeC)
    }
}
Run Code Online (Sandbox Code Playgroud)

我们来试试吧

let triangle = Triangle(edgeA: 5, edgeB: 5, edgeC: 5)
triangle.isEquilateral // true
Run Code Online (Sandbox Code Playgroud)

要么

let triangle = Triangle(edgeA: 2, edgeB: 2, edgeC: 1)
triangle.isEquilateral // false
Run Code Online (Sandbox Code Playgroud)

  • 那绝对是美丽的!谢谢。请告诉我一些事情。为什么我不能只说return edgeA == edgeB == edgeC? (2认同)
  • @AllocSystems不客气。语法`edgeA == edgeB == edgeC`在Swift中无效。但是,如果您想避免在代码中使用的元组,可以编写`edgeA == edgeB && edgeB == edgeC`。 (2认同)

Raj*_*r R 8

只读属性是带有getter但没有的属性setter。它总是用于返回一个值。

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
    }
}
Run Code Online (Sandbox Code Playgroud)