Self
può essere utilizzato come il tipo di ritorno di un metodo:Usa Sé come tipo generico
func doSomething() -> Self {}
E 'in qualche modo possibile utilizzare Self
come un tipo generico come questo?
func doSomething() -> Wrapper<Self> {}
Esempio
Sarebbe bello se potessi sottoclasse ChristmasPresent e lasciare che hanno una funzione che restituisce un wrapped
WrappedPresent con il generico insieme a tutto ciò che la sottoclasse era.
class ChristmasPresent {
func wrapped() -> WrappedPresent<Self> {
return WrappedPresent(present: self)
}
}
class WrappedPresent<T: ChristmasPresent> {
var present: T
init(present: T) {
self.present = present
}
}
class ToyCar: ChristmasPresent {}
let wrappedToyCar = ToyCar().wrapped() // Inferred to be: WrappedPresent<ToyCar>
Cosa rappresenterebbe questo vincolo? Dove è registrato questo vincolo generico? Come viene dichiarato Wrapper? Se è 'Wrapper', possiamo restituire 'Wrapper ', forse .. –
cmyr
C'è una ragione per cui non conosci il tipo di "Sé" al momento? Forse non sto pensando abbastanza bene. È sempre possibile sostituire "Self" con il nome effettivo della classe – bjtitus
Ho aggiunto un esempio :). – Rengers