簡體   English   中英

Swift 泛型。 如何指定輸出類型?

[英]Swift generics. How to Specify output type?

例如,我有enum ,我想要存檔的是每個enum case可以給我一些不同的輸出類型,讓我們說一個函數。 代碼示例:

protocol MyType: Codable {
    var id: String {get set}
}

struct Type1: MyType {
    var id: String
    var name:String
}


struct Type2: MyType {
    var id: String
    var amount: Int
}


enum ReturnType {
    case first, second
    //Option 1
    func getElement() -> MyType {
        switch self {
        case .first:
            return Type1(id: "1", name: "Name")
        case .second:
            return Type2(id: "2", amount: 10)
        }
    }

    //Some crap is here - don't pay attention
    func test<T:MyType>(data: T) -> T {
        return data
    }
}

//Option 2
func getElement(ofType type: ReturnType) -> MyType {
    switch type {
    case .first:
        return Type1(id: "1", name: "Name")
    case .second:
        return Type2(id: "2", amount: 10)
    }
}




let test1 = ReturnType.first.getElement() as! Type1
let test2 = ReturnType.second.getElement()
let test3 = getElement(ofType: .first)

所以目前只有test1Type1test2test3MyType我想存檔強類型而不用as!強制它as!

在此處輸入圖片說明

我試圖用泛型來做,但沒有取得任何成功..有什么想法嗎? 非常感激! 謝謝!

您可以執行以下操作:

enum ReturnType {
    case first, second
    //Option 1
    func getElement<T: MyType>() -> T {
        switch self {
        case .first:
            return Type1(id: "1", name: "Name") as! T
        case .second:
            return Type2(id: "2", amount: 10) as! T
        }
    }

}

//Option 2
func getElement<T: MyType>(ofType type: ReturnType) -> T {
    switch type {
    case .first:
        return Type1(id: "1", name: "Name") as! T
    case .second:
        return Type2(id: "2", amount: 10) as! T
    }
}

之后,當您調用 func 時,您只需要聲明您想要變量的類型:

let test1: Type1 = ReturnType.first.getElement()
let test2: Type2 = ReturnType.second.getElement()
let test3: Type1 = getElement(ofType: .first)

希望它有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM