I was reading the textbook "iOS 14 Programming for Beginners" by Armad Sahar. There are codes below in a MapDataManager class which I was stuck for days.
import Foundation
import MapKit
class MapDataManager: DataManager {
fileprivate var items: [RestaurantItem] = []
var annotations: [RestaurantItem] {
return items
}
func fetch(completion:(_ annotations:[RestaurantItem]) ->()){
if items.count > 0 { items.removeAll() }
for data in load(file: "MapLocations") {
items.append(RestaurantItem(dict: data))
}
completion(items)
}
func currentRegion(latDelta: CLLocationDegrees, longDelta: CLLocationDegrees) -> MKCoordinateRegion {
guard let item = items.first else {
return MKCoordinateRegion()
}
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)
return MKCoordinateRegion(center: item.coordinate, span: span)
}
}
My question is on the fetch function. According to my understanding, the fetch function is accepting another function as variable, which is named as completion
, and I am supposed to declare the "type" of the function after the :
after completion
, which should be ([RestaurantItem]) -> ([RestaurantItem])
to me, because we try to input a [RestaurantItem]
array and just copy and output a new [RestaurantItem]
array.
But now it seems that (_ annotations:[RestaurantItem]) -> ()
becomes the "type" of the completion function and the input variable type is (_ annotations:[RestaurantItem])
, which does not look like a type to me at all. I thought a type could be Int
, String
, [RestaurantItem]
etc., what exactly is type _ annotations:[RestaurantItem]
???
And why is the returning parameter Void ()
? Apparently the completion handler has the return
keyword that returns an item of type [RestaurantItem]
!!!
Please help... I am novice with Swift and I don't have friends around who could help me with that...
Bosco