翻译能力有限,如有不对的地方,还请见谅!希望对Swift的学习者有所帮助,使用的编写工具:JQNote
这章节介绍集合的另一种类型Set,写作Set<Element>, Element是存储的类型。与Array不同,Set没有类似的简写格式。
创建并且初始化一个空的Set:
varletters =Set<Character>()
print("letters is of typeSet<Character>with \(letters.count)items.")
// Prints "letters is of type Set<Character> with 0 items.”
创建一个Set,通过一个Array:
varfavoriteGenres:Set<String>= ["Rock", "Classical", "Hip hop"]
由于该Set已经特定了值类型为String,所以它只允许存储String值。一个Set类型不能够仅仅通过一个Array来推断类型,所以,必须明确声明Set类型。然而,因为Swift有类型推断,所以如果使用一个包含相同类型值的Array来初始化Set,那么就不需要写存储类型了,上面的例子可以简写为:
var favoriteGenres:Set = ["Rock", "Classical", "Hip hop"]
因为Array中所有的值都为String类型,所以Swift可以推断出favoriteGenres的正确类型为Set<String>.
获取和修改Set
你可以获取和修改一个Set,通过它的方法和属性。
获取Set的存储项的数量,可以使用它的只读属性count:
print("I have \(favoriteGenres.count)favorite music genres.")
// Prints "I have 3 favorite music genres.
使用isEmpty属性来判断是否Set的count属性为0:
if favoriteGenres.isEmpty{
print("As far as music goes, I'm not picky.")
} else{
print("I have particular music preferences.")
}
// Prints "I have particular music preferences.”
检查Set是否包含某个特殊项,使用 contains(_:)方法
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// Prints "It's too funky in here.”
遍历Set
你可以使用for-in来遍历Set中的所有值:
for genrein favoriteGenres {
print("\(genre)")
}
// Jazz
// Hip hop
// Classical”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 4)”。 iBooks.
Set是无序的集合,为了以特定顺序遍历Set,可以使用sorted()方法,该方法返回一个 使用<操作符排序过的Array:
for genrein favoriteGenres.sorted() {
print("\(genre)")
}
// Classical
// Hip hop
// Jazz”