我有一个数组,例如["Apple", "Banana", "Blueberry", "Eggplant"]
,我想把它转换成如下字典:
[
"A" : ["Apple"],
"B" : ["Banana", "Blueberry"],
"C" : [],
"D" : [],
"E" : ["Eggplant"]
]
我在Xcode 7 beta 4上使用Swift 2.谢谢!
答案 0 :(得分:7)
仅使用Swift 2对象和方法,并使用字母表中每个字母的键:
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0) })
let words = ["Apple", "Banana", "Blueberry", "Eggplant"]
var result = [String:[String]]()
for letter in alphabet {
result[letter] = []
let matches = words.filter({ $0.hasPrefix(letter) })
if !matches.isEmpty {
for word in matches {
result[letter]?.append(word)
}
}
}
print(result)
答案 1 :(得分:4)
我在Xcode playground中编写了这个:
import Foundation
var myArray = ["Apple", "Banana", "Blueberry", "Eggplant"]
var myDictionary : NSMutableDictionary = NSMutableDictionary()
for eachString in myArray as [NSString] {
let firstCharacter = eachString.substringToIndex(1)
var arrayForCharacter = myDictionary.objectForKey(firstCharacter) as? NSMutableArray
if arrayForCharacter == nil
{
arrayForCharacter = NSMutableArray()
myDictionary.setObject(arrayForCharacter!, forKey: firstCharacter)
}
arrayForCharacter!.addObject(eachString)
}
for eachCharacter in myDictionary.allKeys
{
var arrayForCharacter = myDictionary.objectForKey(eachCharacter) as! NSArray
print("for character \(eachCharacter) the array is \(arrayForCharacter)")
}
答案 2 :(得分:3)
我发现这个问题帮助我更好地理解了我一直在思考的一些概念。这是基于可接受的正确答案的替代方案,该答案稍微简洁并且以编程方式生成字母表。这是Xcode 7中的Swift 2。
let words = ["Apple", "Banana", "Blueberry", "Eggplant"]
let alphabet = (0..<26).map {n in String(UnicodeScalar("A".unicodeScalars["A".unicodeScalars.startIndex].value + n))}
var results = [String:[String]]()
for letter in alphabet {
results[letter] = words.filter({$0.hasPrefix(letter)})
}
print(results)
我相信但不确定let alphabet
行可以更简洁。
答案 3 :(得分:2)
这是我的解决方案。适用于纯Swift 2和O(n)时间,其中n是单词列表的长度(假设字典是作为哈希表实现的)。
var dictionary: [String : [String]] = [ "A" : [], "B" : [], "C" : [], "D" : [],
"E" : [], "F" : [] /* etc */ ]
let words = ["Apple", "Banana", "Blueberry", "Eggplant"]
for word in words
{
let firstLetter = String(word[word.startIndex]).uppercaseString
if let list = dictionary[firstLetter]
{
dictionary[firstLetter] = list + [word]
}
else
{
print("I'm sorry I can't do that Dave, with \(word)")
}
}
print("\(dictionary)")
答案 4 :(得分:0)
我刚刚制作了这样一个有用的数组扩展,它可以根据对象的选定属性将对象数组映射到字符索引对象的字典。
extension Array {
func toIndexedDictionary(by selector: (Element) -> String) -> [Character : [Element]] {
var dictionary: [Character : [Element]] = [:]
for element in self {
let selector = selector(element)
guard let firstCharacter = selector.firstCharacter else { continue }
if let list = dictionary[firstCharacter] {
dictionary[firstCharacter] = list + [element]
} else {
// create list for new character
dictionary[firstCharacter] = [element]
}
}
return dictionary
}
}
extension String {
var firstCharacter : Character? {
if count > 0 {
return self[startIndex]
}
return nil
}
}