[swift-users] Pass Value of Variable to a Function

Jens Alfke jens at mooseyard.com
Tue Sep 6 23:56:42 CDT 2016

> On Sep 6, 2016, at 9:39 PM, Michael Sheaver via swift-users <swift-users at swift.org> wrote:
> I know that in some languages, if you prepend the passed parameter with a '$', as in $propertyName, the receiving function knows to use the contents of the variable named propertyName (in this case "calendar") instead of the literal string "propertyName". 

No, you can’t do that. The languages I think you’re referring to — PHP, Perl — are interpreted scripting languages. Very different beasts, where everything is dynamic and looked up at runtime. (Generally all objects are implemented as dictionaries with property names as keys, making it easy to look up properties by name.) Swift is more like C or C++.

Now, Objective-C has a fairly dynamic runtime that allows you to do this. Objects have a method valueForKey that takes a string and finds a property of the object with that name and returns its value. You can do this in Swift (on Apple platforms) if the class inherits from NSObject or has the @objc attribute. But this isn’t “pure” Swift; it’s an Objective-C feature you’re accessing through bridging.

Generally, there are other patterns that are used to get this sort of effect in languages that aren’t so dynamic (like C++ for example.) But we’d need to know more about the higher-level problem you’re trying to solve, to give advice on that.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160906/deb0d3a2/attachment.html>

More information about the swift-users mailing list