首页 > 解决方案 > 如何在 Swift 中将类作为参数传递

问题描述

在java中,我们可以做到这一点

public Object setClass(String JSONString, Class clazz){
  return JSON.parseObject(JSONString,clazz)
}

但是在 Swift 中,我应该怎么做才能将类作为参数传递。就像

public func decodeData(dataValue : Data, decodeClass: AnyClass){
        do {
            let json = try JSONDecoder().decode(decodeClass, from: dataValue)
            let resultData = json.info;
        }catch{

        }
    }

标签: jsonclass

解决方案


您将需要在此处使用泛型:

    func decode<T: Decodable>(data: Data, type: T.Type){
        do {
            let json = try JSONDecoder().decode(type, from: data)
        } catch {
            //
        }
    }

当你想打电话时,你可以使用.self符号:

decode(data: data, type: String.self)
decode(data: data, type: [String].self)
decode(data: data, type: [Int].self)

推荐阅读