簡體   English   中英

Swift泛型函數接受枚舉

[英]Swift generic function accepting enums

我的情況似乎很簡單。 我嘗試編寫漂亮的可重用代碼來產生錯誤。

代碼邏輯似乎很好。 我們僅在運行時訪問初始化的屬性。 但是編譯器會拋出常見錯誤:

實例成員'jsonValue'不能用於類型'T'

那是我的代碼:

import Foundation

protocol ResponseProtocol {

    static var key: String { get }
    var jsonValue: [String : Any] { get }

}

struct SuccessResponse {

    let key = "success"

    enum EmailStatus: ResponseProtocol {

        case sent(String)

        static let key = "email"

        var jsonValue: [String : Any] { 
            switch self {
            case .sent(let email): return [EmailStatus.key : ["sent" : email]]
            }
        }
    }

    func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : T.jsonValue]
    }

}

我確實希望此代碼能夠正常工作。 'cos現在我有這個的“硬編碼”版本。

jsonValue是方法參數“ response”的屬性,而不是T的類屬性

protocol ResponseProtocol {

    static var key: String { get }
    var jsonValue: [String : Any] { get }

}

struct SuccessResponse {

    let key = "success"

    enum EmailStatus: ResponseProtocol {

        case sent(String)

        static let key = "email"

        var jsonValue: [String : Any] {
            switch self {
            case .sent(let email): return [EmailStatus.key : ["sent" : email]]
            }
        }
    }

    func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : response.jsonValue]
    }

}

使用response.jsonValue代替。

func generateResponse<T: ResponseProtocol>(_ response: T) -> [String : Any] {
        return [key : response.jsonValue]
}

暫無
暫無

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

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