在Swift中的advancedBy 3.代码转换

时间:2016-11-03 12:56:48

标签: swift syntax migration

我无法使代码生效。我正在阅读AppCoda教程,这段代码是用swift 2编写的。 它应该使用数组中的第一个字母组成一个dictorionary

    func createAnimalDict() {
    for animal in animals {
        // Get the first letter of the animal name and build the dictionary
        let animalKey =
animal.substringToIndex(animal.startIndex.advancedBy(1))
        if var animalValues = animalsDict[animalKey] {
            animalValues.append(animal)
            animalsDict[animalKey] = animalValues
        } else {
            animalsDict[animalKey] = [animal]
} }
    // Get the section titles from the dictionary's keys and sort them in
ascending order
    animalSectionTitles = [String](animalsDict.keys)
    animalSectionTitles = animalSectionTitles.sort({ $0 < $1 })
}

它应该给我一个像gictonary一样的dictonary

animalsDict["B"] = ["Bear", "Black Swan", "Buffalo"]
animalsDict["C"] = ["Camel"]

但我不能让这段代码起作用。我试图自己转换,但它不起作用(我是初学者)

func createAnimalDict() {
    for animal in animals {
        // Get the first letter of the animal name and build the dictionary
        let animalKey = animal.substring(to: animal.index(animal.startIndex, offsetBy: 1))
        if var animalValues = animalsDict[animalKey] {
            animalValues.append(animal)
            animalsDict[animalKey] = animalValues
        } else {
            animalsDict[animalKey] = [animal]
        } }
    // Get the section titles from the dictionary's keys and sort them in ascending order
    animalSectionTitles = [String](animalsDict.keys)
    animalSectionTitles = animalSectionTitles.sorted(by: { $0 < $1 })
}

0 个答案:

没有答案