[swift-users] Pass Value of Variable to a Function
Michael Sheaver
msheaver at me.com
Tue Sep 6 21:35:31 CDT 2016
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.
I posted this question on StackOverflow, and got the following that does work:
let calendar2 =
(currentLocale as NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))
It does seem odd to me that we must do some crazy Objective-C gymnastics to make it work. It would seem logical to have a computed property on the Any type named, let's say, contentsOf that would return or pass the contents of the variable to the called function. For example, to use the original code sample above, we could use:
let calendar2 = currentLocale.propertyName.contentsOf
or something similar. Thus currentLocale.propertyName would pass the literal "propertyName", whereas currentLocale.propertyName.contentsOf would pass the contents "calendar".
Does anyone else agree that we need this functionality, or am I way out in left field on this? Or is this already possible and I haven't yet figured it out?
Sincerest Regards,
Michael
Michael Sheaver
msheaver at me.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160906/549517cf/attachment.html>
More information about the swift-users
mailing list