I'm dabbling in swift after a long time away and I've hit an issue that I can't figure out. I'm trying two different ways to add items to a dictionary and getting some different results.
I was initially adding values to a dictionary by doing:
userInfo = ["username":username]
userInfo = ["email":email]
userInfo = ["password":password]
I would then print("\(userInfo)")
but it would only contain password.
I then tried switching it up to:
userInfo!["username"] = username
userInfo!["email"] = email
userInfo!["password"] = password
but this resulted in fatal error: unexpectedly found nil while unwrapping an Optional value
for username
I finally switched it to the following configuration
userInfo = ["username":username]
userInfo!["email"] = email
userInfo!["password"] = password
and everything prints put. Whats up with that?
Full implementation:
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
}
}