我在swift项目中有一个方法定义:
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
}
我在做以下事情:
问题是 - 我无法解决以下错误:
objective-c中的类似方法完美无缺:
+ (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
}
有什么想法吗?
更新1:
正如答案所示,我将函数参数 - 用户名和密码声明为var,但后来我开始收到这些编译错误:
要解决这个问题,我确实输入了类型,但又出现了另一个错误:
强制向下转发,低于错误:
仍然无能为力:(
终于解决了:)
if let dataDictionary = dataDict {
username = dataDictionary[kKeychainUserNameKey] as! String?
password = dataDictionary[kKeychainUserPwdKey] as! String?
}
答案 0 :(得分:8)
默认情况下,函数参数是常量。
将可变参数明确定义为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
}
答案 1 :(得分:2)
您应该将用户名和密码声明为var
。默认值为let
。
class func fireGetRequest(urlString: String!, var username: String?, var password: String?, completionBlock:(NSDictionary)->Void) {
// ...
}
另请参阅:The Swift Programming Language: Functions
常量和变量参数
默认情况下,函数参数是常量。尝试从该函数体内更改函数参数的值会导致编译时错误。这意味着您无法错误地更改参数的值。
但是,有时函数可以使用参数值的变量副本。您可以通过将一个或多个参数指定为变量参数来避免在函数内自己定义新变量。变量参数可用作变量而不是常量,并为函数提供参数值的新的可修改副本。