首页 文章

Swift 3:无法从Dictionary中解包可选?

提问于
浏览
-1

好的,我不知道这里发生了什么 . 我有一个字典下面的字典:

var animals = ["max": "z", "Royal": nil] //store key pairs

如果不打印“可选”,我无法在键值对中打印值的值 .

我已经尝试使用 ! !! 并将其作为字符串进行转换以及以下内容:

var animalsToReturn = [String]()

        if animals[selected]! != nil
        {
            if let pairName = animals[selected]
            {
                print("\(pairName)")

                print("has pair",selected, animals[selected]!)

//trying to append to another array here
                animalsToReturn.append("\(animals[selected]!)")
                animalsToReturn.append(selected)
            }
        }
        else {
            print("no pair")
        }

我检查以确保值不是nil,因此如果我打开它不会崩溃 . 但这是打印的,并且可选的单词附加到我的其他数组:

enter image description here

4 回答

  • 0
    func addAnimal(_ animal: String) {
        guard let animal = animals[animal] else {
            print("No pair")
            return
        }
        animalsToReturn.append(animal ?? "")
    }
    
  • 0

    您已将 nil 作为值包含在内,因此字典值的类型不是String而是 Optional<String> . 但是从字典中获取键值本身就是一个可选项 . 因此:

    • 如果您的条目存在且最终是String,则它是 Optional<Optional<String>> 并且您必须将其解包两次 .

    • 如果您的条目存在且最终是 nil ,则它是可选包装 nil .

    • 如果您的输入不存在,则为 nil .

    您可以按如下方式测试:

    func test(_ selected:String) {
        var animals = ["max": "z", "Royal": nil]
        if let entry = animals[selected] { // attempt to find
            if let entry = entry { // attempt to double-unwrap
                print("found", entry)
            } else {
                print("found nil")
            }
        } else {
            print("not found")
        }
    }
    test("max") // found z
    test("Royal") // found nil
    test("glop") // not found
    

    对这个例子的考虑将回答你原来的问题,即“我不知道这里发生了什么” .

  • 4

    animals[selected]Optional<Optional<String>> 因为你正在存储 nil . 您可以:

    • Double使用 if let! 两次打开您的值 .

    • 将字典类型更改为 [String: String] (而不是 [String: String?] ),从而避免 nil 值 .

    • 展平字典,删除 nil 值,然后将其作为 [String: String] 访问

    您可以使用this question中的代码展平字典 .

  • 0

    请将其括在支架中并使用双重展开 . 试试这个 : -

    animalsToReturn.append("\((animals[selected])!!)")
    

    tried in playground

相关问题