将项目添加到具有不同结果的字典的不同方式

时间:2016-04-29 02:18:06

标签: swift2

经过很长一段时间后,我正在快速地涉足我,我遇到了一个我无法弄清楚的问题。我正在尝试两种不同的方法将项目添加到字典中并获得一些不同的结果。

我最初通过执行以下操作为字典添加值:

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
    }
}

1 个答案:

答案 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
    }
}