gpt4 book ai didi

swift - 是否可以在子类中要求一个可选变量?

转载 作者:搜寻专家 更新时间:2023-11-01 07:03:33 24 4
gpt4 key购买 nike

假设我有一个类 Place,如下所示:

class Place{
let name:String
let description:String
let location:CLLocation?
}

location 变量是可选的。

是否可以创建此类的子类,其中 location 变量是必需的

如果我从 Place 中删除位置变量,这将是可能的,只需这样做:

class LocatedPlace:Place{
let location:CLLocation
}

但是有没有办法在类中拥有一个可选变量,并在子类中使相同的变量成为必需的?

我已经尝试过override let location:CLLocation,但收到消息:不能用存储属性“location”覆盖

最佳答案

正如在对您的问题的评论中所讨论的,您不能在子类中使 location 成为非可选的,因为那样会违反 Liskov Substitution Principle .

CLLocation?CLLocation 是不同的类型,就像 StringCLLocation 是不同的类型一样,您不会不期望能够使 location 成为 LocatedPlace 中的 String

您可以做的是通过对象初始化器强制要求 location 值并隐藏父类(super class)初始化器:

class Place{
let name:String
let description:String
let location:CLLocation?

init(name: String, description: String, location: CLLocation? = nil) {
self.name = name
self.description = description
self.location = location
}
}

class LocatedPlace: Place {

private override init(name: String, description: String, location: CLLocation? = nil) {
super.init(name: name, description: description, location: location)
}

init(name: String, description: String, location: CLLocation) {
super.init(name: name, description: description, location: location)
}
}

请注意,LocatedPlace 实例的 location 属性仍然是可选的,您需要在引用它时解包它。

关于swift - 是否可以在子类中要求一个可选变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49602237/

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