Swift 中返回 nil 的字典值

Dictionary value returning nil in Swift

在此代码中,我试图从字符串中提取工作日。我创建了一个名为 dayDictionary 的字典来更快地访问工作日

dayDictionary 已完美填充,但我无法访问该元素,它总是返回 nil

词典访问代码片段是

for word in components {
        //print(String (word))

        if previous == "to" {
            //print("Hi end")
            endIndex = dayDictionary[String (word)] ?? -1
            break
        }

        if word == "to" {
            //print("Hi Start")

            startIndex = dayDictionary[previous] ?? -1
            continue
        }

        if let validIndex = dayDictionary[String (word)] {
            duration += [validIndex]
            print("Valid")
        }

        previous = String (word)
    }

为了更好的理解,这里是完整的代码

func findWeekDays(sentence: String, weekdays: [String]) -> [Int] {
    var dayDictionary: [String : Int] = [:]

    for index in 0..<weekdays.count {
        dayDictionary[weekdays[index]] = index
    }

    print(dayDictionary)

    sentence.lowercased()
    let components = sentence.split{ ![=12=].isLetter }

    var duration: [Int] = []

    var startIndex: Int = -1
    var endIndex: Int = -1
    var previous: String = ""

    for word in components {
        //print(String (word))

        if previous == "to" {
            //print("Hi end")
            endIndex = dayDictionary[String (word)] ?? -1
            break
        }

        if word == "to" {
            //print("Hi Start")

            startIndex = dayDictionary[previous] ?? -1
            continue
        }

        if let validIndex = dayDictionary[String (word)] {
            duration += [validIndex]
            print("Valid")
        }

        previous = String (word)
    }

    //print("\(startIndex), \(endIndex)")

    if startIndex != -1 && endIndex != -1 {
        if startIndex > endIndex {
            for index in startIndex...6 {
                duration += [index]
            }

            for index in 0...endIndex {
                duration += [index]
            }
        }

    }

    duration.sort()

    if duration.count == 0 {
        duration += [0, 1, 2, 3, 4, 5, 6]
    }

    return duration
}

func userInput() {
    let weekdays: [String] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

    let userSting: String = "Set alarm Monday to Friday"

    let dayIndex: [Int] = findWeekDays(sentence: userSting, weekdays: weekdays)

    for index in dayIndex {
        print("\(weekdays[index])")
    }
}

userInput()

您应该使用 dayDictionary[word.description.lowercased()] 而不是 dayDictionary[String(word)]

我尝试使用 Playground 并在 for 循环中添加了一些 print 行 ->

for word in components {
    print("word is: \(word)")
    print("components is: \(components)")
    print("previous is: \(previous)")
    print("dayDictionary is: \(dayDictionary)")
    print("item in dayDict is: \(dayDictionary[word.description.lowercased()])")

    if previous == "to" {
        print("Hi end")
        endIndex = dayDictionary[String(word)] ?? -1
        break
    }

    if word == "to" {
        print("Hi Start")

        startIndex = dayDictionary[previous] ?? -1
        continue
    }

    if let validIndex = dayDictionary[word.description.lowercased()] {
        duration += [validIndex]
        print("Valid")
    }

    previous = String(word)
    print("---------------------------------------")
}

则输出为:

1st iteration

word is: Set
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: 
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
---------------------------------------

2nd iteration

word is: alarm
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Set
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
---------------------------------------

3rd iteration

word is: Monday
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: alarm
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: Optional(0)
Valid
---------------------------------------

4th iteration

word is: to
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Monday
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: nil
Hi Start

5th iteration

word is: Friday
components is: ["Set", "alarm", "Monday", "to", "Friday"]
previous is: Monday
dayDictionary is: ["tuesday": 1, "wednesday": 2, "saturday": 5, "monday": 0, "thursday": 3, "sunday": 6, "friday": 4]
item in dayDict is: Optional(4)
Valid
---------------------------------------

请看第三次和第五次迭代。我们可以从 dayDictionary.

中获取该项目