다음과 같이 빈 Set을 만들 수 있다.
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// "letters is of type Set<Character> with 0 items." 출력
set을 array로 초기화할 수 있다.
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres는 3개의 아이템을 가진다.
set에 있는 아이템들에 접근하거나 수정하기 위해 메소드와 프로퍼티를 사용한다.
set에 몇가지의 아이템이 있는지 알기 위해서는 read-only 프로퍼티인 count를 사용한다.
print("I have \(favoriteGenres.count) favorite music genres.")
// "I have 3 favorite music genres." 출력
Boolean값을 리턴하는 isEmpty 프로퍼티를 사용해 set이 비었는지 아닌지를 알 수 있다.
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
// "I have particular music preferences." 출력
set에 insert(_:) 메소드를 사용해 새로운 아이템을 추가할 수 있다.
favoriteGenres.insert("Jazz")
// favoriteGenres 에는 "Jazz"라는 아이템이 추가되었다.
set에 remove(_:) 메소드를 사용해 아이템을 지울 수 있다.
remove 메소드를 사용하면 지워진 값을 반환하지만, 만약 존재하지않는 값을 지우려하면 nil을 반환한다.
모든 아이템들을 지우고 싶다면 removeAll 메소드를 사용한다.
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// "Rock? I'm over it." 출력
set이 특정 아이템을 가지고 있는지를 체크하려면 contains(_:) 메소드를 사용한다.
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// "It's too funky in here." 출력
set에 있는 값들은 for-in loop를 사용해 순회 할 수 있다.
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hop
Swift의 set은 순서를 사용하지 않기에 특정 순서대로 순회하고 싶다면 sorted() 메소드를 사용해야한다. < 연산자를 사용해 요소들을 정렬한다.
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
// Classical
// Hip hop
// Jazz