在调用`type(of:xxx)`时,Swift中的`(val:string)类型到底是什么

问题描述 投票:1回答:2

我正在对特定的自定义类型运行跟随功能:

    let mirror = Mirror(reflecting: self)
    print("self \(self)");

    for (propName, propValue) in mirror.children {
        print("propname \(propName) ... \(propValue)", type(of: propValue))
    }

并且正在打印出来

self UserAuthInput.userEmail(val: [email protected])
propname Optional("userEmail") ... (val: "[email protected]") (val: String)

我很难把(val: string)类型的含义作为Swift newb来抓。我知道它来自这样的定义:

    public enum UserAuthInput {

        case userEmail(val: String)

        case userPhone(val: String)
    }

但是我的问题是,

1)如何从[email protected]类型对象(val: string)中解析propValue

2)如何检查此特定的self是否为enum类型,因此需要特殊处理?

谢谢!

ios swift swift3 thrift
2个回答
0
投票

这是一个元素元组。这可以通过使用另一个镜子来反映孩子的价值来确认:

let mirror = Mirror(reflecting: UserAuthInput.userEmail(val: "[email protected]"))
for (propName, propValue) in mirror.children {
    print("propname \(propName!) ... \(propValue)", type(of: propValue))
    let subMirror = Mirror(reflecting: propValue)
    print(subMirror.displayStyle!) // tuple

    // this is one way you can get its value
    print(subMirror.children.first!.value) // [email protected]
}

通常,您不能创建一个元素的元组,所以我对此也感到非常惊讶。由于不能使用类型(val: String) in in code,因此无法仅通过强制转换来获取关联值的值。我上面显示的一种方法是使用另一面镜子。

这与2个或更多关联值的情况一致,这也使propValue为元组类型。

public enum UserAuthInput {

    case userEmail(val: String, val2: String)

    case userPhone(val: String)
}

let mirror = Mirror(reflecting: UserAuthInput.userEmail(val: "[email protected]", val2: "hello"))
for (_, propValue) in mirror.children {
    print(type(of: propValue) == (val: String, val2: String).self) // true
}

要检查镜像是否正在反映枚举,请检查displayStyle

if mirror.displayStyle == .enum {
    // enum!
}

0
投票

您没有描述您的类型(镜像),所以有些猜测。

如果问题是如何提取字符串:

for (propName, propValue) in mirror.children {
    if case .userEmail(let mail) = XXXX { // The value to match. Is it mirror here ?
        print(mail)
    }
    print("propname \(propName) ... \(propValue)", type(of: propValue))
    }
© www.soinside.com 2019 - 2024. All rights reserved.