我在Swift 2中使用此代码。
extension PHFetchResult: Sequence {
public func makeIterator() -> NSFastEnumerationIterator {
return NSFastEnumerationIterator(self)
}
}
自从我升级到Swift 3
通用Objective-C类的扩展无法在运行时访问类的通用参数
我不知道如何解决这个问题。非常感谢任何帮助!
答案 0 :(得分:1)
此处报告了问题:https://bugs.swift.org/browse/SR-1576
但最终你不能在Swift 3.0中使用for in
和PHFetchResult。让我们看一些例子:
let collections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
let collectionLists = PHCollectionList.fetchCollectionLists(with: .momentList, subtype: .momentListYear, options: nil)
let assets = PHAsset.fetchAssets(with: .image, options: nil)
您可以使用PHFetchResult的内置枚举(我推荐的解决方案):
collections.enumerateObjects(_:) { (collection, count, stop) in
//...
}
collectionLists.enumerateObjects(_:) { (collectionList, count, stop) in
//...
}
assets.enumerateObjects(_:) { (asset, count, stop) in
//...
}
或者通过索引访问每个对象:
for idx in 0 ..< collections.count {
let collection = collections[idx]
// ...
}
for idx in 0 ..< collectionLists.count {
let collectionList = collectionLists[idx]
// ...
}
for idx in 0 ..< assets.count {
let asset = assets[idx]
// ...
}
答案 1 :(得分:1)
从Realm中拉出来,你可以通过扩展你想要符合Sequence的子类并将makeIerator
函数放在那里来解决这个问题。
// Sequence conformance for ClassA is provided by ProtocolX's `makeIterator()` implementation.
extension ClassA: Sequence {}
extension ProtocolX {
// Support Sequence-style enumeration
public func makeIterator() -> RLMIterator {
return RLMIterator(collection: self)
}
}
您可以在https://github.com/realm/realm-cocoa/blob/master/Realm/Swift/RLMSupport.swift
查看完整代码答案 2 :(得分:0)
您可以在错误报告中使用包装类型suggested by Swift engineer Jordan Rose:
import Photos struct ResultSequence<Element: AnyObject>: Sequence { var result: PHFetchResult<Element> init(_ result: PHFetchResult<Element>) { self.result = result } func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self.result) } } func test(_ request: PHFetchResult<PHCollection>) { for elem in ResultSequence(request) { print(elem) } }
答案 3 :(得分:-1)