我正在定义一个打印出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<?>
?
答案 0 :(得分:1)
你可以使用String description = rssFeed.getDescription("description");
Document doc = Jsoup.parse(html);
Elements img = doc.select("img");
String url = img.attr("src");
- 基于这样的......
String description = rssFeed.getDescription("description");
Document doc = Jsoup.parse(html);
Elements img = doc.select("img");
String url = getImgSrc(imgs);
private String getImgSrc(Elements imgs) {
for (int j = 0; j < imgs.size(); j++) {
Element img = imgs.get(j);
if (img.hasAttr("src")) {
return img.attr("src");
}
}
return null;
}
查看http://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/