2016-10-27 62 views
2

我想要一個定義一些方法和屬性的協議。但是,符合所述協議的不同類別之間的屬性類型和方法返回類型可能會有所不同。例如:A.getContent()可能會返回類型String的值,但B.getContent()可能會返回類型爲Int的值。在我的例子中,我使用了Any這個類型。這可能在Swift中嗎?或者這是一個完全錯誤的方法?也許用泛型?來自協議方法的不同返回類型

protocol Content { 
    func getContent() -> any 
} 

class A: Content { 
    func getContent() -> String { 
     return "Im a String" 
    } 
} 

class B: Content { 
    func getContent() -> Int { 
     return 1234 
    } 
} 
+1

看看[Swift編程語言指南中的關聯類型部分](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26 -ID189):) – Hamish

+0

也許與泛型。 – matt

回答

1

您可以使用泛型和元類型:

protocol Content { 
    func getContent<T>(ofType: T.Type) -> T? 
} 

class A: Content { 
    func getContent<T>(ofType: T.Type) -> T? { 
     return "Im a String" as? T ?? nil 
    } 
} 

class B: Content { 
    func getContent<T>(ofType: T.Type) -> T? { 
     return 1234 as? T ?? nil 
    } 
} 

let aClass = A() 
let aValue = aClass.getContent(ofType: String.self) // "Im a String" 

let bClass = B() 
let bValue = bClass.getContent(ofType: Int.self) // 1234 
4

我認爲你正在尋找有關泛型的協議。 可以一種動態與associatedtype相關聯,例如

protocol Content{ 
    associatedtype T 
    func getContent()-> T 
} 

class A: Content { 
    func getContent() -> String { 
     return "Hello World" 
    } 
} 

class B: Content { 
    func getContent() -> Int { 
     return 42 
    } 
} 

A().getContent() //"Hello World" 
B().getContent() //42 

如果當你把類型的類太陽內容的功能後,看看這個例子中,協議內容將是一個類型

+0

看起來不錯!問題是我不能和它一起工作。例如,在另一個類中,我嘗試'func addContent(content:Content){...}'但Xcode顯示:'Protocol'Content'只能用作通用約束,因爲它具有自我或相關類型要求' – Mick

+0

相同只是試圖創建一個數組:'var contents = [Content]()' – Mick

+1

@Mick這是因爲與相關類型'String'有關的Content與完全不同於Content的類型具有關聯類型Int, 。沒有真正的解決方法,他們只是不兼容。 – Alexander