My question comes from this apple tutorial project: https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
Landmark is a modal struct:
struct Landmark: Hashable, Codable , Identifiable{
....
var id: Int
var name: String
var park: String
var state: String
var description: String
...
}
A list of Landmarks are loaded from a json file.
var landmarks: [Landmark] = load("landmarkData.json")
The load function is a generic function:
func load<T: Decodable>(_ filename: String) -> T {
...
file = Bundle.main.url(forResource: filename, withExtension: nil)
data = try Data(contentsOf: file)
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
...
}
The following is content of file "landmarkData.json":
[
{
"name": "Kuring-gai",
"category": "Forest",
"city": "Sydney",
"state": "NSW",
"id": 1000,
"isFeatured": true,
"isFavorite": true,
"park": "Kuring-gai National Park",
"coordinates": {
"longitude": -116.166868,
"latitude": 34.011286
},
"description": "forest.",
"imageName": "kuringai"
},
...
]
The Landmark is not passed to the function "load" as a parameter. How is the type of T is decided? Is the type decided by the returned value, when it is called? Thanks!
[Landmark], by writing:var landmarks: [Landmark]. It's conform toDecodableso, it's "deducing the rest". - Larme