gpt4 book ai didi

final var 和 non-final var 之间的快速区别 |最终让和非最终让

转载 作者:IT王子 更新时间:2023-10-29 05:19:07 25 4
gpt4 key购买 nike

final 变量和非 final 变量的区别:

var someVar = 5
final var someFinalVar = 5

let someLet = 5
final let someFinalLet = 5

最佳答案

final 修饰符在 Swift Language Reference 中描述。 ,它说

final

Apply this modifier to a class or to a property, method, or subscript member of a class. It’s applied to a class to indicate that the class can’t be subclassed. It’s applied to a property, method, or subscript of a class to indicate that a class member can’t be overridden in any subclass.

这意味着没有 final 我们可以这样写:

class A {
var x: Int {return 5}
}
class B : A {
override var x: Int {return 3}
}
var b = B()
assert(b.x == 3)

但是如果我们在 A 类中使用 final

class A {
final var x: Int {return 5}
}
class B : A {
// COMPILER ERROR
override var x: Int {return 3}
}

然后会发生这种情况:

$ swift final.swift 
final.swift:6:18: error: var overrides a 'final' var
override var x: Int {return 3}
^
final.swift:2:15: note: overridden declaration is here
final var x: Int {return 5}

关于final var 和 non-final var 之间的快速区别 |最终让和非最终让,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com