我需要在swift中"只读"的帮助。我尝试了各种方法,但根本无法弄清楚如何在没有错误的情况下进行编译。这是我的想法。
创建一个名为iSequiral的纯计算属性,该属性检查三角形的所有三个侧面是否相同,如果不是,则返回true,如果不是。
var isEquilateral: Int {
}
如果您想要"只读"存储的属性,请使用 private(set)
:
private(set) var isEquilateral = false
如果它是从其他属性计算的属性,那么,是的,使用计算属性:
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
只读属性是具有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
}
}