Capslock puts the horse before the cart:
Is there some way to initialize this "city" variable before the property initializer?
Commit this rule to memory! All vars in a struct must be initialized before you can use any of them.
You are attempting to initialize the searchString
var using the city
var. You can't use the city
var until all the vars in the struct have been initialized.
This might be a great use case for computed vars.
struct API {
// Cool! Define a city! It's the first to get initialized.
// Plot twist! It may NOT be the first var initialized.
var city = "Cottington" // Don't forget your towel!
// Swift must initialize ALL vars in a struct,
// before the struct can be used.
// Whilst this is AFTER the city declaration above, Swift does
// NOT guarantee the order in which vars are initialized.
// Consequently, Swift cannot create the var badQueryItem
// because it uses another var named city.
// Indeed, city may not yet exist.
var badQueryItem = URLQueryItem(name: "City", value: city)
// Computed vars are not calculated until needed.
// This will happen after a struct is initialized.
var queryCityItem: URLQueryItem {
URLQueryItem(name: "City", value: city)
}
}
Keep coding!
Please return here and share with the community how you solved this problem.
Variable Names
Also, take a moment and review your var
names.
If my team were providing feedback during a sprint code review, we might question variable and function names.
- Why does the function
locationForecast()
return a URL? Its name suggests it returns a weather forecast for a location! Consider renaming to locationURL
and perhaps making it a computed var.
- Variable
searchString
is not a String
at all. It's a URLQueryItem
object. Plus it's configured only for a city. Consider renaming to cityQueryItem
.