是否可以在子类中要求可选变量?

时间:2018-04-01 20:16:46

标签: swift

我们说我有一个班级k,看起来像这样:

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

2 个答案:

答案 0 :(得分:2)

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

CLLocation?CLLocation是不同的类型,正如StringCLLocation是不同的类型,您不会期望能够{{1} } location中的String

您可以做的是通过强制LocatedPlace值强制隐藏超类初始值来通过对象intialiser强制执行您的要求:

location

请注意,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) } } 实例的location属性仍然是可选的,您需要在引用它时将其解包。

答案 1 :(得分:0)

在不知道你真正要做什么的情况下,我在这里建模:

import CoreLocation

protocol Place {
    var name: String { get }
    var description: String { get }
    var location: CLLocation? { get }
}

struct LocatedPlace: Place {
    let name: String
    let description: String
    var _location: CLLocation

    var location: CLLocation? { return _location }
}