Подтвердить что ты не робот

Преобразование Swift Array в словарь с индексами

Я использую Xcode 6.4

У меня есть массив UIViews, и я хочу конвертировать в словарь с ключами "v0", "v1".... Например:

var dict = [String:UIView]()
for (index, view) in enumerate(views) {
  dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]

Это работает, но я пытаюсь сделать это в более функциональном стиле. Думаю, это беспокоит меня, что мне нужно создать переменную dict. Я хотел бы использовать enumerate() и reduce() следующим образом:

reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
  dict["v\(enumeration.index)"] = enumeration.element // <- error here
  return dict
}

Это выглядит приятнее, но я получаю ошибку: Cannot assign a value of type 'UIView' to a value of type 'UIView?' Я пробовал это с другими объектами UIView (т.е.: [String] -> [String:String]), и я получаю ту же ошибку.

Любые предложения по очистке?

4b9b3361

Ответ 1

попробуйте вот так:

reduce(enumerate(a), [String:UIView]()) { (var dict, enumeration) in
    dict["\(enumeration.index)"] = enumeration.element
    return dict
}

Xcode 8 • Swift 2.3

extension Array where Element: AnyObject {
    var indexedDictionary: [Int:Element] {
        var result: [Int:Element] = [:]
        for (index, element) in enumerate() {
            result[index] = element
        }
        return result
    }
}

Xcode 8 • Swift 3.0

extension Array  {
    var indexedDictionary: [Int: Element] {
        var result: [Int: Element] = [:]
        enumerated().forEach({ result[$0.offset] = $0.element })
        return result
    }
}