1
votes

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!

1
Actually Generic type is decided by Passsing the value type. - Kudos
You tell the compiler what's the return value, it's a [Landmark], by writing: var landmarks: [Landmark]. It's conform to Decodable so, it's "deducing the rest". - Larme

1 Answers

2
votes

Swift type inference is able to determine what type load should return because the type is explicitely stated in the declaration of landmarks.

You will get an error if you omit the type :

var landmarks = load("landmarkData.json") // Generic parameter 'T' could not be inferred

but you can also write :

var landmarks = load("landmarkData.json") as [Landmark]

And if you want to read more on that matter you can check-out this article