[Pitch] Named subscripts 2


(Tony Freeman) #1

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

another option would be use set/get functions, but it doesn't feel right.

Thank you


(Karl) #2

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

···

On 13 Jan 2017, at 10:43, Tony Freeman via swift-evolution <swift-evolution@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

another option would be use set/get functions, but it doesn't feel right.

Thank you

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


(Tony Freeman) #3

Thank you for your answer, but i just feel that options should be a property. I'm ok with my current solution but it can be simplified with named subscript.