Dev*_*shi 1 immutability downcast swift
我在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
}
Run Code Online (Sandbox Code Playgroud)
我在这里做以下事情:
问题是 - 我无法解决以下错误:
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
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
更新1:
正如答案所示,我将函数参数 - 用户名和密码声明为var,但后来我开始收到这些编译错误:
为了解决这个问题,我确实输入了类型,但又出现了另
关于力量向下转发,低于错误:
仍然无能为力:(
终于解决了:)
if let dataDictionary = dataDict {
username = dataDictionary[kKeychainUserNameKey] as! String?
password = dataDictionary[kKeychainUserPwdKey] as! String?
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,函数参数是常量.
明确定义可变参数为 var
斯威夫特2
class func fireGetRequest(urlString: String!, var username: String?, var password: String?, completionBlock:(NSDictionary)->Void)
Run Code Online (Sandbox Code Playgroud)
斯威夫特3
class func fireGetRequest(urlString: String!, username: String?, password: String?, completionBlock:(NSDictionary)->Void){
var username = username
var password = password
//Other code goes here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2265 次 |
| 最近记录: |