我有一个想要转换成字典的数组,我声明了一个函数来实现它,但是每次编译时都会收到这个错误:“不能用'String.SubSequence‘(也就是’Substring‘)类型的参数下标类型'[String : String]’的值”。
我的代码是
let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
var animalsDict = [String: [String]]()
var animalSectionTitles = [String]()
func createAnimalDict() {
for animal in animals {
let secondLetterIndex = animal.index(animal.startIndex, offsetBy: 1)
let animalKey = animal[..<secondLetterIndex]
if var animalValues = animalsDict[animalKey] {
animalValues.append(animal)
animalsDict[animalKey] = animalValues
}else {
animalsDict[animalKey] = [animal]
}
}
animalSectionTitles = [String](animalsDict.keys)
animalSectionTitles = animalSectionTitles.sorted(by: { $0 < $1 })
}我希望在转换到用这个字典填充一个表视图后得到这个字典,它的键指向节标题,它的值引用行的标题。
let animals: [String: [String]] = ["B" : ["Bear", "Black Swan", "Buffalo"],
"C" : ["Camel", "Cockatoo"],
"D" : ["Dog", "Donkey"],
"E" : ["Emu"],
"G" : ["Giraffe", "Greater Rhea"],
"H" : ["Hippopotamus", "Horse"],
"K" : ["Koala"],
"L" : ["Lion", "Llama"],
"M" : ["Manatus", "Meerkat"],
"P" : ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"],
"R" : ["Rhinoceros"],
"S" : ["Seagull"],
"T" : ["Tasmania Devil"],
"W" : ["Whale", "Whale Shark", "Wombat"]]发布于 2020-02-18 15:45:25
你只需像这样使用init(grouping:by:) Dictionary's initializer,
var animalsDict = Dictionary(grouping: animals) { String($0.first!) }
var animalSectionTitles = animalsDict.keys.sorted()输出:
print(animalsDict) //["G": ["Giraffe", "Greater Rhea"], "P": ["Panda", "Peacock", "Pig", "Platypus", "Polar Bear"], "E": ["Emu"], "H": ["Hippopotamus", "Horse"], "K": ["Koala"], "L": ["Lion", "Llama"], "R": ["Rhinoceros"], "D": ["Dog", "Donkey"], "B": ["Bear", "Black Swan", "Buffalo"], "M": ["Manatus", "Meerkat"], "W": ["Whale", "Whale Shark", "Wombat"], "S": ["Seagull"], "T": ["Tasmania Devil"], "C": ["Camel", "Cockatoo"]]
print(animalSectionTitles) //["B", "C", "D", "E", "G", "H", "K", "L", "M", "P", "R", "S", "T", "W"]发布于 2020-02-18 15:45:30
您所需要做的就是将Substring,即animalKey转换为String,您的代码就像预期的那样工作。
let animalKey = String(animal[..<secondLetterIndex])https://stackoverflow.com/questions/60284473
复制相似问题