[swift-users] Why can't Swift instance methods call class methods without qualification?

Nicholas Outram nicholas.outram at icloud.com
Sun Jul 3 01:25:48 CDT 2016


Good point.

Again, from an educator perspective, one view is to think of the Class itself as a singleton object in memory, with its own set of iVars and methods that operate upon them. Although declared and defined in one source, when you visualise as objects / relationships in memory, one model is to see each instance as a small island with references back to a common shared singleton object (the class). 
The prefix seems consistent with this model.

Now this may / may not match reality, but I find it's helpful to have that clear separation, especially for new learners, and Swift is a good entry language in this respect.
(Similarly I like the way closures sometimes force the developer to use the self prefix as well).


Sent from my iPad

> On 1 Jul 2016, at 19:06, Kate Stone <k8stone at apple.com> wrote:
> 
>>> On Jul 1, 2016, at 11:01 AM, Jens Alfke via swift-users <swift-users at swift.org> wrote:
>>> 
>>> 
>>> On Jul 1, 2016, at 10:28 AM, Nicholas Outram via swift-users <swift-users at swift.org> wrote:
>>> 
>>> class methods may mutate "mutable static variables” (singletons), which are dangerous in multi-threaded code.
>> 
>> This is the same argument zh ao made. But instance methods may also mutate static variables, so the fact that you’re calling a class method doesn’t make the call any more dangerous.
>> 
>> Moreover, mutating instance variables can be just as dangerous for multithreaded code (and is a more frequent source of bugs IMHO).
>> 
>> Really, the only significant difference is that a class method can’t modify instance variables, so from that perspective it’s actually a bit safer than an instance method call!
> 
> Though that isn’t strictly true for singleton patterns and other reasons why class variables might include references to instances.
> 
> I believe there’s real value in being explicit about referencing class members.  It helps both the reader of the code and it makes writing code with typical IDE conveniences like code completion less cluttered and more informative. Unfamiliar class methods won’t be included in lists of suggestions where they might look like they operate on the current instance.
> 
> Kate Stone k8stone at apple.com
>  Xcode Low Level Tools
> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160703/be666ef0/attachment.html>


More information about the swift-users mailing list