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:
Problem is - I am clueless on resolving below errors:
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:
To resolve this I did type casting but again another error:
On force downcasting, below error:
Still clueless :(
Finally solved :)
if let dataDictionary = dataDict {
username = dataDictionary[kKeychainUserNameKey] as! String?
password = dataDictionary[kKeychainUserPwdKey] as! String?
}
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
}