5

Is there a smarter/more proper way compared to what I am doing? I created a dictionary and go on enumerating and filling the year/month/date by looking at each fetched asset.

        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
        }
KalanyuZ
  • 672
  • 6
  • 15

1 Answers1

0

I suggest to use a Dictionary grouping directly, is more safe and auto-managed, as explained here: https://developer.apple.com/documentation/swift/dictionary/3127163-init

This is can be your optimized code:

let fetchedAssets = Dictionary(grouping: <#assets-array#>) { asset -> DateComponents in
  return Calendar.current.dateComponents([.day, .year, .month], from: (asset.creationDate)!)
}
print( fetchedAssets )

You'll receive in console something like this:

(lldb) po fetchedAssets.first
▿ Optional<(key: DateComponents, value: Array<Assets>)>
  ▿ some : 2 elements
    ▿ key : year: 2021 month: 5 day: 18 isLeapMonth: false 
      - year : 2021
      - month : 5
      - day : 18
      - isLeapMonth : false
    ▿ value : 1 element
      ▿ 0 : Assets
        - 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 

(lldb)
Dharman
  • 30,962
  • 25
  • 85
  • 135
elp
  • 8,021
  • 7
  • 61
  • 120