0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

`toDictionary` by Extension of SequenceType

Last updated at Posted at 2016-03-23

Xcode7.3にしたら、closureとかの引数をvarにすると警告が出るようになっちゃいましたね。Swift3からは正式に出来なくなるようです。
今までは、arrayからdictionaryを作るときはreduce使ってたんですが、varじゃないと書きにくいですね。それならいっその事、extensionでやってみました。

SequenceType+toDictionary.swift
extension SequenceType {
  func toDictionary<K, V>() -> [K: V] {
    var dictionary: [K: V] = [:]
    self.forEach { e in
      if let kv = e as? (K, V) {
        dictionary[kv.0] = kv.1
      }
    }
    return dictionary
  }

  func toDictionary<K, V>(transform: (element: Self.Generator.Element) -> (key: K, value: V)?) -> [K: V] {
    var dictionary: [K: V] = [:]
    self.forEach { e in
      guard let (key, value) = transform(element: e) else {
        return
      }
      dictionary[key] = value
    }
    return dictionary
  }

  func toDictionary<K, V>(combine: (value1: V, value2: V) -> V?) -> [K:  V] {
    var dictionary: [K: V] = [:]
    self.forEach { e in
      guard let kv = e as? (K, V) else {
        return
      }
      let (key, value2) = kv
      if let value1 = dictionary[key] {
        dictionary[key] = combine(value1: value1, value2: value2)
      } else {
        dictionary[key] = value2
      }
    }
    return dictionary
  }

  func toDictionary<K, V>(transform transform: (element: Self.Generator.Element) -> (key: K, value: V)?, combine: (value1: V, value2: V) -> V?) -> [K:  V] {
    var dictionary: [K: V] = [:]
    self.forEach { e in
      guard let (key, value2) = transform(element: e) else {
        return
      }
      if let value1 = dictionary[key] {
        dictionary[key] = combine(value1: value1, value2: value2)
      } else {
        dictionary[key] = value2
      }
    }
    return dictionary
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?