[英]Can I downcast in Swift in a “for in” control structure?
I have a sorted array of details generated from an NSSet. 我从NSSet生成了一系列详细信息。 I want to iterate through them to print them out. 我想遍历它们以打印出来。 Right now I do this: 现在,我这样做:
for aDetail in sortedDetails! {
let someDetail = aDetail as! Detail
if someDetail.parentDetail != "" {
print("----\(someDetail.name)")
} else {
print("\(someDetail.name)")
}
}
Is there a cleaner way to do the "let someDetail = aDetail as! Detail" in the "for-in" definition instead? 有没有一种更干净的方法来代替“ for-in”定义中的“ let someDetail = aDetail as!Detail”? (ie Force the downcast in the definition of the for-in loop rather than create a separate variable that's cast?) (即在for-in循环的定义中强制向下转换,而不是创建一个强制转换的单独变量?)
This works but it feels clunky. 这可行,但感觉笨拙。
If the array's contents are guaranteed to be convertible to Detail
, you can cast the array: 如果保证数组的内容可以转换为Detail
,则可以强制转换数组:
for aDetail in sortedDetails as! [Detail] {
if aDetail.parentDetail != "" {
print("----\(aDetail.name)")
} else {
print("\(aDetail.name)")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.