我正在定义一个打印 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 子句,但我不能,因为它是一种涉及泛型的类型。编译器消息是:Protocol 'CollectionType' can only be used as a generic constraint because it has Self or associated type requirements
我只需要迭代和 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/
关于swift - 如何检查实例是否实现了 CollectionType?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34152297/