Aggiornamento: Swift 3 consente di utilizzare Self
da altri tipi, grazie a SE-0068 – Expanding Swift Self to class members and value types.'Self' è disponibile solo in un protocollo o come risultato di un metodo di classe
È possibile tornare "Self" da una funzione di classe:
extension NSObject {
class func makeOne() -> Self {
return self()
}
}
modo da poter fare:
let set : NSCountedSet = NSCountedSet.makeOne()
Tuttavia, i seguenti due non si compilano:
extension NSObject {
class func makeTwo() -> (Self, Self) {
return (self(), self())
}
class func makeMany() -> [Self] {
return [self(), self(), self(), self(), self()]
}
}
L'errore è:
<REPL>:11:34: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
class func makeTwo() -> (Self, Self) {
^~~~
NSObject
<REPL>:11:40: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
class func makeTwo() -> (Self, Self) {
^~~~
NSObject
<REPL>:15:35: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
class func makeMany() -> [Self] {
^~~~
NSObject
Qualcuno sa di un modo per dichiarare che una funzione di classe restituisce più istanze della classe stessa?
Da segnalare che non c'è alcuna vera ragione per cui questo non dovrebbe essere possibile - sotto il cofano, per un dato 'statica() -> Metodo Self' su un determinato tipo' T', il compilatore genera semplicemente una funzione '(T.Type) -> T'. Quando viene chiamato, il chiamante lancia il risultato sul tipo effettivo sul quale viene chiamato il metodo. Il compilatore è in grado di eseguire la conversione di un array di istanze di sottoclassi in una matrice di istanze di superclasse e una conversione di tuple potrebbe essere banalmente eseguita dalla scomposizione. Quindi, mentre tecnicamente qualcosa che il compilatore * potrebbe * fare, semplicemente non lo supporta (ancora). – Hamish