我正在定义一个打印出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,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/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。