Swift: Modifying parameters using the inout modifier

The notion of InOut parameters  just popped up in a conversation over on #swift-lang on irc.freenode.net (hi Lily!). Thought I’d share due to the coolness of modifying variables.Apple writes, “If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter”. Here’s a really trivial example, one that updates a CGRect’s origin to zero, for those times when you want to do coordinate system work.

// InOut function that converts rect
func ConvertForBounds(inout rect : CGRect)
{
    rect.origin = CGPointZero
}

var rect = CGRectMake(10, 20, 30, 40)
var bounds = rect // copy
ConvertForBounds(&bounds)
rect
bounds

Comments are closed.