当前位置 : 主页 > 手机开发 > 其它 >

swift – 如何检查实例是否实现了CollectionType?

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在定义一个打印出Any实例的函数.如果它是NSArray或CollectionType,它会打印出它拥有的项目数量和最多10个项目: static func prettyPrint(any: Any) - String { switch any { case is NSArray: let array = any
我正在定义一个打印出Any实例的函数.如果它是NSArray或CollectionType,它会打印出它拥有的项目数量和最多10个项目:

static func prettyPrint(any: Any) -> String {
    switch any {
    case is NSArray:
        let array = any as! NSArray
        var result: String = "\(array.count) items ["
        for i in 0 ..< array.count {
            if (i > 0) {
                result += ", "
            }
            result += "\(array[i])"
            if (i > 10) {
                result += ", ..."
                break;
            }
        }
        result += "]"
        return result

    default:
        assertionFailure("No pretty print defined for \(any.dynamicType)")
        return ""
    }
}

我想为任何CollectionType添加一个case子句,但我不能,因为它是一个涉及泛型的类型.编译器消息是:协议’CollectionType’只能用作通用约束,因为它具有Self或关联类型要求
我只需要迭代和count属性来创建打印字符串,我不关心集合包含的元素的类型.

如何检查CollectionType<?>?

你可以使用Mirror – 基于这样的东西……

func prettyPrint(any: Any) -> String {
    var result = ""
    let m = Mirror(reflecting: any)
    switch m.displayStyle {
    case .Some(.Collection):
        result = "Collection, \(m.children.count) elements"
    case .Some(.Tuple):
        result = "Tuple, \(m.children.count) elements"
    case .Some(.Dictionary):
        result = "Dictionary, \(m.children.count) elements"
    case .Some(.Set):
        result = "Set, \(m.children.count) elements"
    default: // Others are .Struct, .Class, .Enum, .Optional & nil
        result = "\(m.displayStyle)"
    }

    return result
}

prettyPrint([1, 2, 3]) // "Collection, 3 elements"
prettyPrint(NSArray(array:[1, 2, 3])) // "Collection, 3 elements"
prettyPrint(Set<String>()) // "Set, 0 elements"
prettyPrint([1:2, 3:4]) // "Dictionary, 2 elements"
prettyPrint((1, 2, 3)) // "Tuple, 3 elements"
prettyPrint(3) // "nil"
prettyPrint("3") // "nil"

查看http://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/

网友评论