Swift: allow instance variables as default parameter variables

Originator:getaaron
Number:rdar://19592727 Date Originated:25-Jan-2015 07:27 AM
Status:Open Resolved:
Product:iOS SDK Product Version:6.1.1
Classification:Enhancement Reproducible:Always
 
Summary:

Instance variables should be allowable as as default parameter variables for a function.

Steps to Reproduce:

1. Create a class with a non-optional property
2. Add a method that takes a default parameter value as an argument
3. Set the non-optional property as the parameter’s default value

Expected Results:

I expect the property’s current value to be used as the parameter’s default value when the function is called.

Actual Results:

The code will not compile.

Note:

Swift appears to be looking for a class variable instead of an instance variable.

Sample Code:

Paste this code into Playground. Try the two different implementations of shrinkPayment(_:)

———— playground code ————

class CreditCard {
    var minimumPayment = 55_00 //in pennies
    var currentBalance = 1_250_00
    
    // This implementation of shrinkPayment works, but is verbose
    
    func shrinkPayment(desiredPayment : Int?) -> Int {
        if let desiredPayment = desiredPayment {
            return currentBalance < desiredPayment ? currentBalance : desiredPayment
        } else {
            return currentBalance < minimumPayment ? currentBalance : minimumPayment
        }
    }
    
    // This implementation of shrinkPayment would be more concise, but doesn't work because instance variables can't be default parameter values

//    func shrinkPayment(desiredPayment : Int = minimumPayment) -> Int {
//        return currentBalance < desiredPayment ? currentBalance : desiredPayment
//    }

    func pay(amount : Int) {
        currentBalance -= amount
    }
}

let visa = CreditCard()

while visa.currentBalance > 0 {
    let payment = visa.shrinkPayment(nil)
    visa.pay(payment)
}

———— end playground code ————

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!