Reputation: 23
I have seen many examples of how to get a value from a plist in swift - however all involve type casting the variable after it is read from the plist. Since we already give the property a type when creating it in the plist, why do we have to type it again? Is there any way to read values from the plist with the type they have in the plist?
For example this is the approach I am using to read the value from a plist:
extension Bundle {
var someVar: String {
return object(forInfoDictionaryKey: "someVar") as? String ?? ""
}
}
Why do I need to cast the variable again as String when I have already typed it as String in the plist?
Upvotes: 2
Views: 740
Reputation: 285092
Please ⌥-click on object(forInfoDictionaryKey
. You will see
Since a property list can contain many different types (array, dictionary, string, url, numeric values, date, data) the return value is optional Any
and you have to cast the type.
Apple provides another approach in URL
: If you get a value from resourceValues(forKeys
with an URLResourceKey
you get also the expected type.
Feel free to write an extension of Bundle
which considers also the actual type.
Upvotes: 1
Reputation: 998
Because your plist is a [String: Any]
dictionary. It can hold values that are not String
and the compiler can't know what is what until you specifically tell it - via the casting you are doing.
Upvotes: 1