如何创建一个接受 Any 类型并输出它的 JSON 字符串化版本的函数?
How do I create a function that takes Any type and outputs the JSON stringified version of it?
我一遍又一遍地使用以下代码将我的数据整形为 JSON 并希望有一个本机可重用函数来实现我可以传递任何内容的相同功能,它将检查它是否可编码并输出 nil 或 String:
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
guard let jsonDateData = try? encoder.encode(dateOfApproval) else {return}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return}
问题的核心似乎是我无法检查发送的 Any 对象是否是可编码的,让我检查具体类型(如下所示):
func shapeData(dataToShape: Any)-> String? {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
if let hi = dataToShape as? String { // I'd prfer to be able to check if it's encodable here instead of a specific type
guard let jsonDateData = try? encoder.encode(hi) else {return nil}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return nil}
return myDateString
} else {
return nil
}
}
我试过if dataToShape is Encodable
,但也没用。
您可以使您的函数通用。这样你的 dataToShape
参数将是一些通用类型,你可以将其限制为 Encodable
:
func shapeData<T>(dataToShape: T) -> String? where T: Encodable {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
guard let jsonDateData = try? encoder.encode(dataToShape) else {return nil}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return nil}
return myDateString
}
我一遍又一遍地使用以下代码将我的数据整形为 JSON 并希望有一个本机可重用函数来实现我可以传递任何内容的相同功能,它将检查它是否可编码并输出 nil 或 String:
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
guard let jsonDateData = try? encoder.encode(dateOfApproval) else {return}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return}
问题的核心似乎是我无法检查发送的 Any 对象是否是可编码的,让我检查具体类型(如下所示):
func shapeData(dataToShape: Any)-> String? {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
if let hi = dataToShape as? String { // I'd prfer to be able to check if it's encodable here instead of a specific type
guard let jsonDateData = try? encoder.encode(hi) else {return nil}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return nil}
return myDateString
} else {
return nil
}
}
我试过if dataToShape is Encodable
,但也没用。
您可以使您的函数通用。这样你的 dataToShape
参数将是一些通用类型,你可以将其限制为 Encodable
:
func shapeData<T>(dataToShape: T) -> String? where T: Encodable {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateStyle = .medium
encoder.dateEncodingStrategy = .formatted(formatter)
guard let jsonDateData = try? encoder.encode(dataToShape) else {return nil}
guard let myDateString = String(data: jsonDateData, encoding: .utf8) else {return nil}
return myDateString
}