在Set中搜索元素的Swift程序
在Swift中,集合是一種無序的、獨特的、不可重復的存儲對象的容器。愛掏網 - it200.com當我們需要搜索集合中是否存在某個元素時,可以利用Set的contains()方法進行查找。愛掏網 - it200.com
Set的contains()方法用于判斷集合中是否包含某個元素。愛掏網 - it200.com其聲明如下:
func contains(_ member: Element) -> Bool
其中,member代表集合中存在的元素,Element是泛型參數。愛掏網 - it200.com該方法返回一個布爾值,true代表集合中包含該元素,false代表集合中不包含該元素。愛掏網 - it200.com
下面是一段Swift代碼示例,演示如何利用contains()方法在Set中查找元素:
var mySet: Set<String> = ["apple", "banana", "orange"]
if mySet.contains("banana") {
print("Set中包含該元素")
} else {
print("Set中不包含該元素")
}
運行結果:
Set中包含該元素
Set中包含自定義對象的搜索
當集合中存儲的元素為自定義對象時,需要重寫該對象的hashValue和操作符,以確保集合中不會有重復的元素。愛掏網 - it200.com下面是一個自定義對象Point的例子:
class Point: Hashable {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
// 重寫hashValue
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
// 重寫==
static func ==(lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
var pointSet: Set<Point> = [Point(x: 1, y: 2), Point(x: 2, y: 3), Point(x: 4, y: 5)]
if pointSet.contains(Point(x: 2, y: 3)) {
print("Set中包含該元素")
} else {
print("Set中不包含該元素")
}
運行結果:
Set中包含該元素
實戰:判斷密碼是否合法
我們可以利用Set的contains()方法來判斷用戶輸入的密碼是否合法。愛掏網 - it200.com假設密碼需要符合以下規則:
- 長度大于等于8位
- 至少包含一個小寫字母
- 至少包含一個大寫字母
- 至少包含一個數字
下面是一個Swift代碼示例:
func isPasswordValid(_ password: String) -> Bool {
if password.count < 8 {
return false
}
if !password.contains(where: { 0.isUppercase }) {
return false
}
if !password.contains(where: {0.isLowercase }) {
return false
}
if !password.contains(where: { $0.isNumber }) {
return false
}
return true
}
let password = "Abc12345"
let invalidPassword = "abc123"
let validChars = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
if isPasswordValid(password) && Set(password).isSubset(of: validChars) {
print("密碼合法")
} else {
print("密碼不合法")
}
if isPasswordValid(invalidPassword) && Set(invalidPassword).isSubset(of: validChars) {
print("密碼合法")
} else {
print("密碼不合法")
}
運行結果:
密碼合法
密碼不合法
結論
本文介紹了Swift中Set的contains()方法,以及如何利用該方法在Set中搜索元素。愛掏網 - it200.com對于包含自定義對象的Set,需要重寫該對象的hashValue和操作符;對于實際應用中的密碼合法性驗證,可以使用Set的isSubset(of:)方法來判斷輸入的密碼包含的字符是否合法。愛掏網 - it200.com
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。