11
15

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.

Swiftで配列(Array)の差分を取得する

Last updated at Posted at 2016-11-15

Swiftで配列(Array)の差分(diff相当)を取得する

出典はこちらです。
Swiftのバージョンが低くそのまま使えなかったので、すこし手直しして共有しておきます。

extension Array where Element: Hashable {
	typealias E = Element
	func diff(_ other: [E]) -> [E] {
		let all = self + other
		var counter: [E: Int] = [:]
		all.forEach { counter[$0] = (counter[$0] ?? 0) + 1 }
		return all.filter { (counter[$0] ?? 0) == 1 }
	}
}

let a = [1, 2, 3, 4]
let b = [8, 2, 3, 9]
let diff1 = a.diff(b) // => [1, 4, 8, 9]
let diff2 = b.diff(a) // => [8, 9, 1, 4]

Swiftで配列(Array)の差分(引き算)をする

Setのsubtract/subtracting相当のメソッドです。
こちらは新しく作りました。
比較のため、利用する配列はEquatableに準拠している必要があります。

extension Array where Element: Equatable {
	typealias E = Element

	func subtracting(_ other: [E]) -> [E] {
		return self.flatMap { element in
			if (other.filter { $0 == element }).count == 0 {
				return element
			} else {
				return nil
			}
		}
	}

	mutating func subtract(_ other: [E]) {
		self = subtracting(other)
	}
}

var a = [1, 2, 3, 4]
let b = [8, 2, 3, 9]

let sub1 = a.subtracting(b)
sub1 // => [1, 4]
a // => [1, 2, 3, 4]
a.subtract(b)
a // => [1, 4]
11
15
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
11
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?