Michael Sheaver Michael Sheaver - 8 months ago 72
Swift Question

Use value of variable for property lookup

I am trying to build a table of current locale properties in code, and have encountered issues with trying to pass the value of a variable to a function:

let currentLocale = Locale(identifier: "en_US")

let calendar1 = currentLocale.calendar // "gregorian (fixed)"

let propertyName = "calendar"
let calendar2 = currentLocale.propertyName // Error: Value of type 'Locale' has no member 'porpertyName'

In the last line of code above, the instance of Locale thinks I am passing it "propertyName" rather than the contents of the variable "calendar".

Is there any way to pass the value of propertyName ("calendar") to the instance of Locale? I know that in other languages, you can prepend the variable name like '$propertyName', and that tells it to read the value of the variable.

I want to keep this pure Swift if possible.


You are looking for some form of key-value coding.

It's a little tricky, in that this is a purely Objective-C feature of Cocoa, so it doesn't work with the Swift overlay class Locale; you will have to cast currentLocale to Objective-C NSLocale. Moreover, NSLocale exposes its attributes through special NSLocale.Key types. After a great deal of casting, I find that this works:

let calendar2 = 
    (currentLocale as NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))

calendar2 is typed as Any but you can cast it down to a String.