Swift中常見的String用法,Array高階使用,Set集合操作

String字符串常見用法
生成字符串
創建字符串
let greeting = "Hello, world!"
let name = String("John")

連接字符串:使用加號(+)或者字符串插值(使用())來將多個字符串連接起來。
var firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName // "John Doe"
let fullName1 = firstName.append(lastName) // "My name is John Doe."
let message = "My name is \(fullName)." // "My name is John Doe."
子字符串查詢,替換,插入,刪除
查找子字符串
let sentence = "Swift is a powerful and intuitive programming language."
if sentence.contains("Swift") {
    // do something
}
let range = sentence.range(of: "powerful") // Optional(Range(10..<18))
var str3 = "123456"
print(str.hasPrefix("123"))
print(str.hasSuffix("456"))

替換字符串
var sentence = "Swift is a powerful and intuitive programming language."
sentence = sentence.replacingOccurrences(of: "powerful", with: "amazing")

字符串刪除
// 666hello_2_3_8884
str4.remove(at: str4.firstIndex(of: "1")!)
// hello_2_3_8884
str4.removeAll { $0 == "6" }
var range = str4.index(str4.endIndex, offsetBy: -4)..<str4.index(before: str4.endIndex)
// hello_2_3_4
str4.removeSubrange(range)

字符串插入
var str = "Hello, world!"
let firstChar = str[str.startIndex] // "H"
let lastChar = str[str.index(before: str.endIndex)] // "!"
str.insert("!", at: str.endIndex) // "Hello, world!!"
字符串轉數組
字符串分割
let names = "John, Jane, Jim"
let arr = names.components(separatedBy: ", ") // ["John", "Jane", "Jim"]
字符串轉其他
let str = "123"
let num = Int(str) // Optional(123)
let uppercased = str.uppercased() // "123"

 

Array數組高階操作
map:對給定數組每個元素,執行閉包中的映射,將映射結果放置在數組中返回。
flatMap:對給定數組的每個元素,執行閉包中的映射,對映射結果進行合併操作,然後將合併操作後的結果放置在數組中返回。
compactMap:對給定數組的每個元素,執行閉包中的映射,將非空的映射結果放置在數組中返回。
compactMap:對給定數組的每個元素,執行閉包中的映射,將非空的映射結果-鍵值對放置在字典中返回。
filter:對給定數組的每個元素,執行閉包中的操作,將符合條件的元素放在數組中返回。
reduce:對給定數組的每個元素,執行閉包中的操作對元素進行合併,並將合併結果返回。
var arr = [1, 2, 3, 4]
// [2, 4, 6, 8]
var arr2 = arr.map { $0 * 2 }
print(arr2)
// [2, 4]
var arr3 = arr.filter { $0 % 2 == 0 }
print(arr3)
// 10
var arr4 = arr.reduce(0) { $0 + $1 }
print(arr4)
// 10
var arr5 = arr.reduce(0, +)
print(arr5)

 

Set集合操作
集合創建
let setA = Set(["a","b","c"])
let setB: Set = ["a","b","c"]
增刪改查
setA.contains("a")
setA.insert("c")
setA.remove("a")
集合運算
let set1 = Set([1,2,3])
let set2 = Set([1,2])

//運算判斷
if set1 == set2 {
    
}
// 子集,超集判斷
set2.isSubset(of: set1)
set1.isSuperset(of: set2)

// 並集,交集
set1.union(set2)
set1.intersection(set2)

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章