【问题标题】:Swift inputing characters and strings into a dictionary快速将字符和字符串输入字典
【发布时间】:2019-02-22 13:50:17
【问题描述】:

我将如何编写一个函数,该函数接受一个字符串数组并输出一个字典,其中每个字符串的第一个字符作为键,其余字符作为对象?

【问题讨论】:

  • 你尝试过什么?展示您的代码以及您面临的问题?

标签: arrays swift xcode function dictionary


【解决方案1】:

为您编写这段代码,而没有从您身边看到任何试验,只是因为您是 StackOverflow 的新手。我看到来自 StackOverflow 的消息:“Corey Townsend 是一位新的贡献者。Be nice...” 因此,我只是对您表示欢迎,这是您的代码。

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"]]

【讨论】:

    【解决方案2】:

    这就是你要找的东西吗?

    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"]]
    

    【讨论】:

    • 输出应该是 ["b": ["all"], "f": ["lower", "ire"], "d": ["og"], "c" : ["ar", "at"], "n": ["otebok"]]
    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 2023-01-28
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多