使用reduce()在Swift中构建字典

时间:2016-04-11 07:14:33

标签: swift dictionary functional-programming reduce

我想使用函数式编程风格构建字典。我的reduce()似乎不起作用 - 我得到了一个致命的错误:在解开一个Optional值时出乎意料地发现了nil"

func loadMoveToCalendarsRules(calendarIndex: Int) -> [String]? {
//    return something like ["phone call", "buzz", "ring"]
    return NSUserDefaults.standardUserDefaults().objectForKey(generateMoveToCalendarsRules_NSUserDefaultsKey(calendarIndex)) as? [String]
}

// Add indeces to an array of any type
func addIndices<T>(toArray: [T]) -> [(index: Int, value: T)] {
    return Array(zip(toArray.indices, toArray))
}

typealias CalendarRules = [EKCalendar : [String]]?
func buildCalendarRules(cals: [EKCalendar]) -> CalendarRules {
    let sortedCals = cals.sort { $0.title.lowercaseString < $1.title.lowercaseString }

    // build move to cal rules.
    let indexedCalList = addIndices(sortedCals)
    // go through the sorted calendars and build a dictionary that associates each calendar with a string array. (These are keywords that apply to the given calendar.)
    let calendarRules = indexedCalList.reduce(nil as CalendarRules) {
        accumulator, nextValue in
        var retVal: [EKCalendar : [String]]? = accumulator
        // if there are values found in NSUserDefaults for this calendar index then retrieve them.
        if let rulesForCurrentCal = loadMoveToCalendarsRules(nextValue.index) {
            retVal![nextValue.value] = rulesForCurrentCal       // fatal error: unexpectedly found nil while unwrapping an Optional value
        }
        return retVal
    }

    print("------------ built calendar rules -------------")
    print(Array(arrayLiteral: calendarRules?.keys))
    print(Array(arrayLiteral: calendarRules?.values))

    return calendarRules
}

0 个答案:

没有答案