swift – 如何检查实例是否实现了CollectionType?
发布时间:2020-12-14 04:30:46 所属栏目:百科 来源:网络整理
导读:我正在定义一个打印出Any实例的函数.如果它是NSArray或CollectionType,它会打印出它拥有的项目数量和最多10个项目: static func prettyPrint(any: Any) - String { switch any { case is NSArray: let array = any as! NSArray var result: String = "(arr
我正在定义一个打印出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或关联类型要求 如何检查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,3])) // "Collection,3 elements" prettyPrint(Set<String>()) // "Set,0 elements" prettyPrint([1:2,3:4]) // "Dictionary,2 elements" prettyPrint((1,3)) // "Tuple,3 elements" prettyPrint(3) // "nil" prettyPrint("3") // "nil" 查看http://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |