最终变量和非最终变量之间的快速差异最终让与非最终让 [英] swift difference between final var and non-final var | final let and non-final let

查看:58
本文介绍了最终变量和非最终变量之间的快速差异最终让与非最终让的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最终变量和非最终变量有什么区别:

What's difference between final variables and non-final variables :

var someVar = 5
final var someFinalVar = 5

let someLet = 5
final let someFinalLet = 5

推荐答案

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,我们可以写:

This means without final we can write:

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

但是如果我们在类A

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}

这篇关于最终变量和非最终变量之间的快速差异最终让与非最终让的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆