Search code examples
swiftimmutabilitydowncast

Unable to modify function parameters within function body


I have a method definition in a swift project:

class func fireGetRequest(urlString: String!, username: String?, password: String?, completionBlock:(NSDictionary)->Void) {
    //check if user passed nil userName
    if username == nil || password == nil {
        // retrieve userName, password from keychain
        // here we have OR check since we have single value from pair it is of no use and can be considered as corrupted data
        // so it is better to retrieve stable data from keychain for further processing
        let (dataDict, error) = Locksmith.loadDataForUserAccount(kKeychainUserAccountName)

        // no error found :)
        // use data retrieved
        if error == nil {
            username = dataDict[kKeychainUserNameKey]
            password = dataDict[kKeychainUserPwdKey]
        }
    }

    // do something with username, password
}

Here I am doing following things:

  1. Checking if any of username, password is nil or not
  2. If any of those is nil then trying to set respective values from a dictionary

Problem is - I am clueless on resolving below errors:

enter image description here

Similar method in objective-c works perfectly:

+ (void)fireGetRequestWithUrlString:(NSString *)urlString userName:(NSString *)username userPwd:(NSString *)password{
    NSDictionary *dataDict = @{kKeychainUserNameKey: @"Some user name", kKeychainUserPwdKey: @"Some password"};

    if (!username || !password) {
        username = dataDict[kKeychainUserNameKey];
        password = dataDict[kKeychainUserPwdKey];
    }

    // do something with username, password
}

Any ideas?

Update 1:

As suggested in answers I declared function parameters- username and password as var but then I started getting these compilation errors:

enter image description here

To resolve this I did type casting but again another error:

enter image description here

On force downcasting, below error:

enter image description here

Still clueless :(

Finally solved :)

if let dataDictionary = dataDict {
                    username = dataDictionary[kKeychainUserNameKey] as! String?
                    password = dataDictionary[kKeychainUserPwdKey] as! String?
                }

Solution

  • Function parameters are constants by default.

    Define the mutable parameters explicitly as var

    Swift 2

    class func fireGetRequest(urlString: String!, var username: String?, var password: String?, completionBlock:(NSDictionary)->Void) 
    

    Swift 3

    class func fireGetRequest(urlString: String!, username: String?, password: String?, completionBlock:(NSDictionary)->Void){
       var username = username
       var password = password
       //Other code goes here
    }