gpt4 book ai didi

swift - 将协议(protocol)<>任意转换为字符串(或其他)

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:12 35 4
gpt4 key购买 nike

我有一个类叫做 User()

class User {
var name: String?
var email: String?
var id: String?
var identification_number: String?
var phone_number: NSMutableArray?
var user_group: String?
var date: NSDate?
}

我想获取类中的所有变量及其各自的值。在这种情况下,我尝试使用 Mirror

func updateProfile(user: User) {

let mirror = Mirror(reflecting: user)

for child in mirror.children {
print("\(child.label!), \(child.value)")
}

}

我的问题是,如何将 child.value 转换为任何其他数据类型,比如 String ?我只发现 child.value 属于 Protocol 'Any'

最佳答案

child.value 具有 Any 类型。从 Any 转换为可选值会带来一些问题,幸运的是 Sandy Chapman 在 this post 中给出了一个非常好的解决方案.

使用他的函数,代码看起来像这样:

func castToOptional<T>(x: Any) -> T? {
return Mirror(reflecting: x).descendant("Some") as? T
}

func updateProfile(user: User) {
let mirror = Mirror(reflecting: user)
for child in mirror.children {
print("\(child.label!), \(child.value)")
if let stringVal = castToOptional(child.value) as String? {
print("Unwrapped a string: \(stringVal)")
} else if let stringVal = child.value as? String {
print("Found a non-optional string: \(stringVal)")
}
}
}

因此,如果您要查找字符串,则需要同时查找可选字符串和非可选字符串。这适用于您需要检查的所有类型。

关于swift - 将协议(protocol)<>任意转换为字符串(或其他),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636854/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com