[swift-evolution] [Pitch] Named subscripts 2

Karl Wagner razielim at gmail.com
Fri Jan 13 10:03:10 CST 2017


> On 13 Jan 2017, at 10:43, Tony Freeman via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello Swift community,
> 
> I found this very useful while wrapping c api, although this may simplify the code in other cases when subscript doesn't have it's own state and(or) share some state form the container.
> 
> here is an example: https://gist.github.com/tonyfreeman/949ce0a9aa374ab6fa2fc7de0dccaa27 <https://gist.github.com/tonyfreeman/949ce0a9aa374ab6fa2fc7de0dccaa27>
> 
> another option would be use set/get functions, but it doesn't feel right.
> 
> Thank you
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

I don’t see why it even needs to have a name in that example. Why not just make it a regular subscript? The meaning should be obvious since you are passing a constant like “SO_REUSEADDR”. You could even make your own “SocketOption” enum to make things nicer:

socket[.allowPortReuse] = true

Subscript declarations are a little weird. They have an implicit “_” as their first parameter name, but you can override that and provide an explicit name. So, you could write your subscript as “subscript(option option: Int32) -> Bool”:

socket[option: SO_REUSEADDR]    // or 
socket[option: .allowPortReuse]

Would that suit your needs?

- Karl


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170113/d8020356/attachment.html>


More information about the swift-evolution mailing list