我试图在我的桌子上添加部分,但我无法将MutableArray
(我的database
包含60个值的)的第一封信写入{ {1}}。
我想创建字母dictionary
,第一个字母作为标题,部分中的行数作为以该字母开头的所有值。
我的代码:
sections
输出:
" A" // 60次
答案 0 :(得分:4)
在
for crime in marrCrimesNames {
crimeFirstLetter = crimeName.characters.first! as AnyObject
print(crimeFirstLetter)
}
您实际上并未使用crime
变量
相反,您只使用crimeName
这就是为什么您会获得" A"一直以来。
尝试改为
for crime in marrCrimesNames {
crimeFirstLetter = crime.Name.characters.first! as AnyObject
print(crimeFirstLetter)
}
现在创建一个这样的字典:
let dict = ["A" : ["Aname1", "Aname2", "Aname3"], "B" : ["Bname1", "Bname2", "Bname3"]]
来自这样的数组:
let array = ["Aname1", "Aname2", "Aname3", "Bname1", "Bname2", "Bname3"]
您可以使用此代码:
let dict = ["A" : ["Aname1", "Aname2", "Aname3"], "B" : ["Bname1", "Bname2", "Bname3"]]
let characters = Array(Set(array.flatMap({ $0.characters.first })))
var result = [String: [String]]()
for character in characters.map({ String($0) }) {
result[character] = array.filter({ $0.hasPrefix(character) })
}
print(result) // output: ["B": ["Bname1", "Bname2", "Bname3"], "A": ["Aname1", "Aname2", "Aname3"]]