Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active April 6, 2017 14:26
Show Gist options
  • Save KentarouKanno/b9b3cf74290500b35e91 to your computer and use it in GitHub Desktop.
Save KentarouKanno/b9b3cf74290500b35e91 to your computer and use it in GitHub Desktop.
Set

Set

★ 値を追加する

var setValue: Set = [1, 2, 3]

// 重複できないので値が追加されない
setValue.insert(2)
//=> {2, 3, 1}

setValue.insert(4)
//=> {2, 3, 1, 4}

★ structでsetを使用する

struct A: Equatable, Hashable {
    var value: String = "1"
    
    init(_ value: String) {
        self.value = value
    }
    
    var hashValue: Int {
        return self.value.hashValue
    }
}

extension A {
    public static func ==(lhs: A, rhs: A) -> Bool {
        return lhs.value == rhs.value
    }
}

var a = [A("1"), A("2"), A("3"), A("1"), A("1"), A("2"), A("4"), A("4"), A("4"), A("4")]


var b = Set<A>(a)
//=> [A(value: "4"), A(value: "2"), A(value: "1"), A(value: "3")]

var c = Set<A>(a).map { $0.value }
//=> ["4", "2", "1", "3"]

var d = Set<A>(a).map { $0.value }.sorted(by: <)
//=> ["1", "2", "3", "4"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment