我将如何编写一个函数,该函数接收一个字符串数组并输出一个字典,其中每个字符串的第一个字符作为键,其余作为对象?
答案 0 :(得分:0)
仅因为您是StackOverflow的新手而为您编写这段代码,而不会看到您的任何尝试。我看到StackOverflow发出的消息是“科里·汤森(Corey Townsend)是新的贡献者。变得很好 ...” 因此,欢迎您的光临,这里就是我的代码。
let arr = ["car", "cat", "dog", "ball", "flower", "notebook", "fire"]
func createDictionaryFromArrayAsCoreyWants(arr:[String]) -> [String:String] {
var dict:[String:String] = [:]
arr.forEach({ (word:String) in
let strKey = String(word.prefix(1))
let startIndex: String.Index = word.index(word.startIndex, offsetBy: 1)
let strValue = String(word[startIndex..<word.endIndex])
dict[strKey] = strValue
print(strKey + " : " + strValue)
})
return dict
}
let d = createDictionaryFromArrayAsCoreyWants(arr: arr)
print(d)
添加
刚刚看到“ Alex Bailer”对另一个答案的评论,因此为您添加了另一个功能。享受...
func createDictionaryFromArrayAsCoreyWants(arr:[String]) -> [String:[String]] {
var dict:[String:[String]] = [:]
arr.forEach({ (word:String) in
let strKey = String(word.prefix(1))
let startIndex: String.Index = word.index(word.startIndex, offsetBy: 1)
let strValue = String(word[startIndex..<word.endIndex])
if let a = dict[strKey] {
dict[strKey] = a + [strValue]
} else {
dict[strKey] = [strValue]
}
print(strKey + " : " + strValue)
})
return dict
}
let d = createDictionaryFromArrayAsCoreyWants(arr: arr)
print(d)
输出:
["d": ["og"], "n": ["otebook"], "b": ["all"], "c": ["ar", "at"], "f": ["lower", "ire"]]
答案 1 :(得分:-1)
这是您要找的吗?
let d = Dictionary(grouping: array, by: {$0.prefix(1)})
带有数组:
let array = ["car", "cat", "dog", "ball", "flower", "notebok", "fire"]
它打印:
["b": ["ball"], "f": ["flower", "fire"], "d": ["dog"], "c": ["car", "cat"], "n": ["notebok"]]
然后,从值中删除第一个字母:
for key in d.keys {
let values = d[key]
let start = String.Index(encodedOffset: 1)
d[key] = values?.compactMap({ String($0[start...]) })
}
输出:
["f": ["lower", "ire"], "d": ["og"], "b": ["all"], "c": ["ar", "at"], "n": ["otebok"]]