我最初通过执行以下操作为字典添加值:
userInfo = ["username":username]
userInfo = ["email":email]
userInfo = ["password":password]
然后我会print("\(userInfo)")
但它只包含密码。
然后我尝试将其切换为:
userInfo!["username"] = username
userInfo!["email"] = email
userInfo!["password"] = password
但这导致fatal error: unexpectedly found nil while unwrapping an Optional value
用户名
我终于将其切换到以下配置
userInfo = ["username":username]
userInfo!["email"] = email
userInfo!["password"] = password
并打印所有内容。那是什么?
全面实施:
nextPressed()
{
if let userInfo:[String:String] = try registrationValidation()
{
print("\(userInfo)")
}
}
func registrationValidation () throws -> [String:String]?
{
var userInfo: [String:String]?
var problems: [ValidationMessage] = []
if let username = usernameField.text
{
let p1 = validateUsername(username)
problems.appendContentsOf(p1)
userInfo = ["username":username]
//userInfo!["username"] = username
//Above results in nil, yet lines below work?
}
if let email = emailField.text
{
let p2 = validateEmail(email)
problems.appendContentsOf(p2)
//userInfo = ["email":email]
userInfo!["email"] = email
}
if let password = passwordField.text
{
let p3 = validatePassword(password)
problems.appendContentsOf(p3)
//userInfo = ["password":password]
userInfo!["password"] = password
}
if !problems.isEmpty{
throw ValidationError(problems:problems)
}
else
{
print("validation succeeded")
return userInfo
}
}
答案 0 :(得分:0)
我认为这是一种更好的方式来实现你想要达到的目标:
func registrationValidation () throws -> [String:String]?
{
var userInfo = [String:String]() // **Initialize an empty dictionary**
var problems: [ValidationMessage] = []
if let username = usernameField.text
{
let p1 = validateUsername(username)
problems.appendContentsOf(p1)
userInfo["username"] = username
}
if let email = emailField.text
{
let p2 = validateEmail(email)
problems.appendContentsOf(p2)
//userInfo = ["email":email] **// This line will result in creating a new dictionary object**
userInfo["email"] = email
}
if let password = passwordField.text
{
let p3 = validatePassword(password)
problems.appendContentsOf(p3)
//userInfo = ["password":password]
userInfo["password"] = password
}
if !problems.isEmpty{
throw ValidationError(problems:problems)
}
else
{
print("validation succeeded")
return userInfo
}
}