簡體   English   中英

如何創建具有可選泛型類型的動態結構

[英]how to create dynamic struct with optional generic type

我為 API 響應創建了一個可解碼的基礎結構。

struct ResponseBaseModel<T: Decodable>: Decodable {
    let status: Bool
    let message: String
    var result: T?

    private enum CodingKeys: String, CodingKey {
        case result, message, success,status,statusCode
    }

     init(from decoder: Decoder) throws {
           let values = try decoder.container(keyedBy: CodingKeys.self)
            if let result = try? values.decode(T.self, forKey: .result) {
                self.result = result
            }
        status = try  values.decode(Bool.self, forKey: .status)
        message = try  values.decode(String.self, forKey: .message)
       }
}

// 這里是 API 響應

{
    "status": true,
    "statusCode": 200,
    "message": "Theater list successfully",
    "result": [
        {
            "id": 1,
            "name": "Galaxy",
            "picture": "https://ctdemo.workpc.online/kshatrainfotech/abol-app/public/storage/images/theaters/default.png",
            "is_notify": false
        }
    ]
}

這是我如何使用它來調用 API

 apimanager.fetch { [weak self] (response: Result<ResponseBaseModel<[Theater]>, ApiError>) in
        self?.handelResponse(response: response) { response in
            switch response {
            case .success(let theaterList):
                self?.theaterViewModels = theaterList.map{ TheaterViewModel(theaterModel: $0)}
                self?.responseHandler(.success(self!.theaterViewModels))
            case .failure(let apiError):
                self?.responseHandler(.failure(apiError))
            }
        }
    }

但某些 API 沒有結果,例如

{ "status": true, "statusCode": 200, "message": "api.DATA_UPDATED_SUCCESS" }

如何使用 ResponseBaseModel 模型處理上述響應。因為在使用 ResponseBaseModel 結構時我必須傳遞任何類型。

ResponseBaseModel<?>

我已經嘗試過ResponseBaseModel<nil>但它沒有用。

我試着稍微簡化一下你的問題,以說明為什么你想要的東西不可能這樣。 考慮以下結構:

struct TestStruct<T> {
    let code:Int
    var value:T?

    init(code:Int) {
        self.code = code
    }
} 

通常你會這樣使用它:

var s = TestStruct<String>(code:42)
s.value = "abc"

print (s) // TestStruct<String>(code: 42, value: Optional("abc"))

現在你說:“哦,我只需要一個 TestStruct 用於一些代碼,根本沒有價值”並嘗試以下操作:

var codeOnly = TestStruct<nil>(code:42)
print (codeOnly)

編譯器抱怨,因為它需要一個專用的value屬性類型。 為什么不起作用? 因為想到以下語句:

let v = codeOnly.value
// or
codeOnly.value = "String"

在這里,編譯器需要知道屬性codeOnly.value是什么類型。 由於它現在不能,因此它不允許無類型的TestStruct

暫無
暫無

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

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