数据类型
基础数据类型
OC封装类型
Swift中Array使用Contains的正确姿势
序列化(json转JSONString)
let wordList = ["11", "22"]
let data = try? JSONSerialization.data(withJSONObject: wordList)
let jsonString = String(data: data, encoding: .utf8)
public extension Encodable {
func toJSONString() -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self) else { return "" }
guard let jsonStr = String(data: data, encoding: .utf8) else { return "" }
return jsonStr
}
}
struct TestModel: Codable {
var name: String = ""
var age: Int = 0
}
let testModel = TestModel(name: "name1", age: 10)
debugPrint(testModel.toJSONString())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
反序列化(json转model)
func jsonToModel<T>(type: T.Type, json: Any) -> T? where T:Codable {
guard let jsonData = try? JSONSerialization.data(withJSONObject: json) else {
return nil
}
guard let model = try? JSONDecoder.init().decode(type, from: jsonData) else {
return nil
}
return model
}