按日期对 PHAsset 获取结果进行分组的智能方法

Kal*_*yuZ 5 ios swift phasset

与我正在做的事情相比,有没有更聪明/更合适的方法?我创建了一个字典,并通过查看每个获取的资产继续枚举和填充年/月/日。

        let assetFetchResult = PHAsset.fetchAssetsInAssetCollection(album, options: assetFetchOptions)
        if assetFetchResult.count > 0 {
            var fetchedAssets = [String:[String:[String:[PHAsset]]]]()
            //[year[month[date:arrayOfPhotos]]]

            assetFetchResult.enumerateObjectsUsingBlock({
                object, index, stop in

                let asset:PHAsset = object as! PHAsset
                let dateComponents = NSCalendar.currentCalendar().components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: asset.creationDate)

                //year group creation
                if fetchedAssets["\(dateComponents.year)"] == nil {
                    fetchedAssets["\(dateComponents.year)"] = [String:[String:[PHAsset]]]()
                }
                //monthly group creation
                if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] == nil  {
                    fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"] = [String:[PHAsset]]()
                }

                //daily group creation
                if fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] == nil  {
                    fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"] = [PHAsset]()
                }

                fetchedAssets["\(dateComponents.year)"]!["\(dateComponents.month)"]!["\(dateComponents.day)"]?.append(asset)
            })
            println(fetchedAssets)
            return fetchedAssets
        }
Run Code Online (Sandbox Code Playgroud)

elp*_*elp 1

我建议直接使用Dictionary grouping,更安全且自动管理,如下所述:https ://developer.apple.com/documentation/swift/dictionary/3127163-init

\n

这可以是您的优化代码:

\n
let fetchedAssets = Dictionary(grouping: <#assets-array#>) { asset -> DateComponents in\n  return Calendar.current.dateComponents([.day, .year, .month], from: (asset.creationDate)!)\n}\nprint( fetchedAssets )\n
Run Code Online (Sandbox Code Playgroud)\n

您将在控制台中收到如下内容:

\n
(lldb) po fetchedAssets.first\n\xe2\x96\xbf Optional<(key: DateComponents, value: Array<Assets>)>\n  \xe2\x96\xbf some : 2 elements\n    \xe2\x96\xbf key : year: 2021 month: 5 day: 18 isLeapMonth: false \n      - year : 2021\n      - month : 5\n      - day : 18\n      - isLeapMonth : false\n    \xe2\x96\xbf value : 1 element\n      \xe2\x96\xbf 0 : Assets\n        - asset : <PHAsset: 0x7fcebcc43740> A86BC4A1-63E3-41EB-897D-695A395531D6/L0/001 mediaType=1/4, sourceType=1, (2112x1590), creationDate=2021-05-18 11:19:23 +0000, location=0, hidden=0, favorite=0, adjusted=0 \n\n(lldb)\n
Run Code Online (Sandbox Code Playgroud)\n