[swift-evolution] Properties with parameters

Ben Rimmington me at benrimmington.com
Sat Apr 23 13:37:10 CDT 2016


Tim Vermeulen via swift-evolution <swift-evolution at ...> writes:

> Properties are great. They allow us to write the more naturally looking
> 
> myButton.hidden = true
> 
> instead of
> 
> myButton.setHidden(true)
> 
> However, they don't take any parameters. That’s why we still have to write
> 
> myButton.setImage(myImage, forState: .Normal)
> 
> instead of
> 
> myButton.imageForState(.Normal) = myImage
> 
> The syntax to write such a function would be pretty straight-forward:
> 
> var imageForState(state: UIControlState): UIImage? {
>     get { … }
>     set { … }
> }

Alternatively, in a Swift 2.2 overlay:

public extension UIButton {
    @nonobjc public subscript(imageForState state: UIControlState) -> UIImage? {
        get {
            return imageForState(state)
        }
        set {
            setImage(newValue, forState: state)
        }
    }
}

myButton[imageForState: .Normal] = myImage

Apparently, C#'s "indexed properties" were rejected by the Swift design team:

<https://github.com/apple/swift/blob/master/docs/proposals/Accessors.rst>

-- Ben


More information about the swift-evolution mailing list