Farewell parameter var

In Swift 3.0, the var keyword in function parameters is being removed. Apparently there was too much confusion of var parameters with the functionality of inout parameters. For more information, see the Swift blog announcementSwift Evolution proposal and swift-evolution-announce post.

If you had function parameters set as vars in your code, this can be a bit of a pain.

I for example had an extension of UIColor that initialized a UIColor with a hex parameter var:

extension UIColor {
    /// A hex must be either 7 or 9 characters (#GGRRBBAA)
    convenience init(var hex: String) {
        /// etc...

The hex parameter was set as a var as I modified it in the process of converting it to an RGB Alpha value.

The first instinct might be just to make your function parameter inout:

    convenience init(inout hex: String) {

However if you pass in a literal to an inout parameter, you’ll see a compiler error:

let color = UIColor(hex: "#4EA2FF")

Cannot convert value of type ‘String’ to expected argument type ‘inout String’

That’s not ideal. Best case scenario is no changes to the calls to the function or the function body itself.

To achieve this, all you need to do is remove `var` from your function parameters, and add a first line, passing in the parameter value to a variable:

extension UIColor {
    /// A hex must be either 7 or 9 characters (#GGRRBBAA)
    convenience init(hex: String) {
        var hex = hex
        /// etc...

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with:
Posted in Swift

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: