[swift-users] Should a queue be value type or reference type?

Jordan Rose jordan_rose at apple.com
Tue Jul 26 11:26:53 CDT 2016


> On Jul 26, 2016, at 00:36, Quinn The Eskimo! via swift-users <swift-users at swift.org> wrote:
> 
> 
> On 25 Jul 2016, at 15:10, 褚 晓敏 via swift-users <swift-users at swift.org> wrote:
> 
>> So what should it be, according to API design guidelines?
> 
> It’s hard to answer this question without more information about your specific context.  However, I think it’s safe to say that Swift expresses a preference for value types.  OTOH, reference types exist for a reason: sometimes you really do want to model shared mutable state.
> 
> My approach to this is to design the data structure as a value type and see how that works out for clients.  If the client code looks good, you’re set.  OTOH, if the client code is painful, you need to rethink.

Rather than look for an answer in the API design guidelines, try choosing between value and reference semantics. If you pass the queue to another part of the program, and that other part of the program pops some things off of it, should that change be reflected in the original queue? Or would you expect passing the queue somewhere to make a completely independent copy? As you say, DispatchQueue clearly works the first way (and should), and Array works the second way (and should). What should your type do, in your application?

One more note: it’s easier to go from value semantics to reference semantics, by making the value be a property of a class instance. So if you make a value-typed queue, you could use it to implement DispatchQueue.

Hope we’ve given you some places to start.
Jordan

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


More information about the swift-users mailing list