gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:38:33 26 4
gpt4 key购买 nike

我正在定义一个打印出 Any 实例的函数.如果它是 NSArrayCollectionType它打印出它有多少个项目,最多 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com