gpt4 book ai didi

swift - 'String' 无法转换为 'DictionaryIndex' 编译器错误,具有非常基本的字典用法

转载 作者:搜寻专家 更新时间:2023-10-31 22:00:45 25 4
gpt4 key购买 nike

我正在尝试制作一个非常简单的字典,将字符串映射到 Swift 中的字符串数组。代码如下所示:

class FirstViewController: UIViewController {

var characters:[String] = []
var adjacency = [String : [String]?]()

override func viewDidLoad() {
super.viewDidLoad()

characters = loadCharacters()
adjacency = loadAdjacency()

var character:String = characters[0]
var adj:[String] = adjacency[character] // This line gives the first compiler error
adj = adjacency["a"] // This line gives the second compiler error

println(adj)
}

func loadCharacters() -> [String] {
return ["a", "b", "c"]
}

func loadAdjacency() -> [String : [String]?] {
return ["a": ["a", "b", "c"], "b": ["b", "c", "d"], "c": ["c", "d", "e"]]
}
}

第一个编译器错误是: 'String' is not convertible to 'DictionaryIndex<String, [(String)]?>'

第二个编译器错误是: '(String, [(String)]?)' is not convertible to '[String]'

据我所知,这两行应该是等效且正确的——我正在使用字符串作为键从字典查找中获取一个字符串数组。我哪里错了?

如果我这样写,代码可以正确编译运行:

class SecondViewController: UIViewController {

var keyArray:[String] = []
var dict = [String : [String]?]()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

keyArray = ["a", "b", "c"]
dict = ["a": ["a", "b", "c"], "b": ["b", "c", "d"], "c": ["c", "d", "e"]]

println(dict[keyArray[1]])

}

}

顺便说一下,我使用的是 Xcode 版本 6.1 (6A1052d),并且运行的是 OSX 10.9.4。我正准备升级到优胜美地,以防我的设置出现异常,但我想我只是遗漏了一些明显的东西。

最佳答案

错误信息在这里不是很有帮助,它与实际问题根本无关....

解决方案一:

var adj/*:[String]??*/ = adjacency[character] // adj is Optional<Optional<[String]>>
adj = adjacency["a"]
println(adj) // Optional(Optional(["a", "b", "c"]))

解决方案 2:

var adj/*:[String]*/ = adjacency[character]!! // adj is [String]
adj = adjacency["a"]!!
println(adj) // [a, b, c]

解决方案 3 - 安全的方法:

if let adj = adjacency[character] { // adj is Optional<String[]>
if let adj2 = adj { // adj2 is String[]
println(adj2)
}
}

关于swift - 'String' 无法转换为 'DictionaryIndex<String, [(String)]?>' 编译器错误,具有非常基本的字典用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27208487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com