/ / Kann eine optionale Variable in einer Unterklasse benötigt werden? - schnell

Kann eine optionale Variable in einer Unterklasse angefordert werden? - schnell

Sagen wir, ich habe eine Klasse Placesieht so aus:

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

Das location-variable ist optional.

Ist es möglich, eine Unterklasse dieser Klasse zu erstellen, in der location-Variable ist erforderlich?

Dies wäre möglich, wenn ich die Standortvariable aus entferne Placeund tat einfach das:

class LocatedPlace:Place{
let location:CLLocation
}

Gibt es eine Möglichkeit, eine optionale Variable in einer Klasse zu haben und diese Variable in einer Unterklasse erforderlich zu machen?

Ich habe versucht override let location:CLLocationaber erhalte die Nachricht: Cannot override with a stored property "location"

Antworten:

2 für die Antwort № 1

Wie in den Kommentaren zu Ihrer Frage erläutert, können Sie dies nicht tun location nicht optional in der Unterklasse, da dies die Liskov-Substitutionsprinzip.

CLLocation? und CLLocation sind verschiedene Typen, genauso String und CLLocation Es gibt verschiedene Typen, und Sie würden nicht in der Lage sein zu machen location ein String im LocatedPlace.

Was Sie tun können, ist die Durchsetzung Ihrer Anforderung durch den Object Intialiser, indem Sie die location Wert obligatorisch und Verstecken des Superklasse-Initialisierers:

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)
}
}

Notiere dass der location Eigentum von LocatedPlace Die Instanz ist immer noch optional, und Sie müssen sie auspacken, wenn Sie darauf verweisen.


0 für die Antwort № 2

Ohne zu wissen, was Sie tatsächlich tun wollen, hier, wie ich das modellieren würde:

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 }
}