Recently, I have read many tutorials and daishen’s blog during my study of Swift. Finally, I put my notes here for easy review
W3cschool -Swift tutorial, YungFan’s brief book (recommended to have a look, some knowledge summary is simply easy to understand)
String & character
1. String
1.1, introduced
The String type in Swift is String, which is a structure with higher performance. Support traversal
1.2. Initialization
Immutable string: let modifier
let str = "hello Objective-C"
Copy the code
Mutable string: var modifier
var str = "hello Swift"
Copy the code
Multiline string
"" Thoughts on the quiet night by Li Bai The moonlight was shining before my bed, and I suspected it was frost on the ground. Looking up the bright moon, lower the head to think of home. "" "Copy the code
Meaning Escapes the string
/* If the string contains a backslash "\", there are two ways to solve the problem: Let STR = "string with escape character backslash" //2, let STR = #" string with escape character backslash "#Copy the code
1.3 common operations
Length: count or length
let str = "12345678"
let len1 = str.count //8
let len2 = (str as NSString).length //8
Copy the code
Concatenation: + or append
let str1 = "abc" + "cde"
var str2 = "abc"
str2.append("cde")
Copy the code
Through:
// let STR = "abcdefg" for STR {print(char)} value) in str.enumerated() { print("\(index) --- \(value)") }Copy the code
Case: lower and uppercased
Let STR = "abcdefg" // all lowercase print(str.lowercased()) // all uppercase print(str.uppercased())Copy the code
Contains or not: contains
let str = "abcdefg"
print(str.contains("cd")) //true
print(str.contains("c")) //true
print(str.contains("o")) //false
Copy the code
Segmentation: components
Let STR = "abcdefg$$aAAA $$BBBB $$CCC "let desc = str.components(separatedBy: "$$") for item in desc { print(item) }Copy the code
Replacement: replacingOccurrences
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let dest = str.replacingOccurrences(of: "$$", with: "**")
print(dest)
Copy the code
Intercepting substring:
// write method 1: Print (sub1) // Print (sub1) // Print (sub1) // Print (sub2) // Print (sub1) // Print (sub2) // Print (sub2) // Print (sub1) // Print (sub2) // Print (sub2) // Print (sub2) // Print (sub1) // Print (sub2) // print(sub2) str.suffix(5) print(sub2)Copy the code
Let STR = "Hello World" // take the first 5 strings of a string, Let index1 = str.index(str.startIndex, offsetBy: Let sub1 = STR [str.startIndex..<index1] print(sub1) Let index2 = str.index(str.endIndex, offsetBy: -1) let sub2 = STR [index2..<str.endIndex] print(sub2) let sub2 = STR [index2..<str.endIndex] print(sub2)Copy the code
2, character,
A character is a single character
let char: Character = "A"
Copy the code
Note:
- Multiple characters will cause an error
- Null characters generate an error
Second, the array
1, the introduction
Swift refers to an Array as an Array. It is a generic set. It is a structure whose elements are ordered and can be repeated
2. Initialize
Immutable arrays: Let modifier
let array : [Any] = ["zhangsan", 18]
Copy the code
Mutable arrays: var modifier
Var array: [String] = [String]()Copy the code
Initialization format (var can be replaced with let)
Var array1: Array<Any> = ["zhangsan", 18] var array2: Array<Any> = ["zhangsan", 18] Var array3 = ["zhangsan", "lisi"] var array4 = ["zhangsan", "lisi"] Array<Any> array4 = ["zhangsan", "18"]Copy the code
An empty array is initialized
Var emptyArray = [String]()Copy the code
Var emptyArray = [] if the type information can be inferredCopy the code
Initialize an array of type Int with size 3 and default values 0
var array = [Int](repeating: 0, count: 3)
print(array) //[0, 0, 0]
Copy the code
3. Common operations
The length of the
array.count
Copy the code
The length of the
array.isEmpty
Copy the code
Increase the data
array.append("zhaoliu")
Copy the code
Insert data
array.insert("haojian", at: 0)
Copy the code
Modify the data
array[0] = "wangqi"
Copy the code
Search data: Value
array[1]
array.first
Copy the code
Reverse order
array.reverse()
Copy the code
Merger: +
Array1 = ["zhang", "wang", "li", "zhao"] array2 = [" SAN ", "si", "Wu "] let array3 = array1 + array2 print(array3) // print: ["zhang", "wang", "li", "zhao"," SAN ", "si", "wu"]Copy the code
Capacity: capacity
Var array = [Int]() for I in 0... var array = [Int]() for I in 0... <8 { array.append(i) print("\(array)\(array.capacity)") }Copy the code
4, traverse
Ordinary traversal
for i in 0.. <array.count { print(array[i]) }Copy the code
The for – way in
for item in array {
print(item)
}
Copy the code
Interval traversal
// for item in array[0..<2] {print(item)}Copy the code
Tuples traversal
let array = ["zhang", "wang", "li", "zhao", "zhou"] for (index, enumerated() {print("\(index) == \(name)")} /* Print: 0 == Zhang 1 == Wang 2 == Li 3 == zhao 4 == zhou */Copy the code
Third, the dictionary
1, the introduction
The Dictionary type in Swift is Dictionary, which is also a generic collection. It is disordered between elements, health cannot be repeated, and others are similar to OC
2. Initialize
Immutable dictionary: let modifier
// dictdict1: Dictionary<String, Any> = ["age": 18,"name": "zhangsan"] // dict2: [String: Any] = ["age": Dict3 = ["age": 18,"name": "zhangsan"] as [String: Any]Copy the code
Mutable dictionary: var modifier
// dictdict1: Dictionary<String, Any> = ["age": 18,"name": "zhangsan"] dict2: [String: Any] = ["age": Dict3 = ["age": 18,"name": "zhangsan"] as [String: dict3 = ["age": 18,"name": "zhangsan"] // dictdict4 = [dictdict4]() // dictdict5 = [:]Copy the code
3. Common operations
The length of the
dict.count
Copy the code
Sentenced to empty
dict.isEmpty
Copy the code
Increase the data
var dict = [String : Int]()
dict["height"] = 18
dict["weight"] = 20
print(dict)
Copy the code
Delete the data
RemoveValue (forKey: "height") dict["height"] = nilCopy the code
Modify the data
// Dict ["height"] = 55 // dict. UpdateValue (99, forKey: "weight")Copy the code
Query data
// Dict ["name"]Copy the code
merge
Var dict1: [String: a] = ["name" : "zhangsan", "age" : 20] var dict2: [String: b] Any] = ["height" : 180, "phone" : For (key) in dict2 {dict1[key] = value} print(dict1) // print: ["height": 180, "name": "zhangsan", "phone": "18888888888", "age": 20]Copy the code
4, traverse
Walk through all the values in the dictionary
for value in dict.values {
print(value)
}
Copy the code
Walk through all the keys in the dictionary
for key in dict.keys {
print(key)
}
Copy the code
Walk through all the key-value pairs
/ / are commonly used for (key, value) in dict {print (" \ (key) = = \ (value) ")}Copy the code
Traversal in enumeration mode
var dict: [String : Any] = ["name" : "zhangsan", "age" : 20, "height" : 180, "phone" : "18888888888"] // Value) for (index, value) in dict.enumerated() {print("\(index) == \(value)")} /* Print: 0 == (key: "phone", value: "18888888888") 1 == (key: "age", value: 20) 2 == (key: "name", value: "zhangsan") 3 == (key: "height", value: 180) */Copy the code
Fourth, tuples
1, the introduction
Swift has a unique data structure that can be used to define a set of data, the data that makes up a tuple can be called an element
2, definitions,
Common writing
Var one = ("zhangsan", 20, "1888888888",180) // The types of the elements of this tuple are: String,Int,String,IntCopy the code
Give the element a name
Var one = (name: "zhangsan", age: 20, phone: "1888888888",height: 180Copy the code
3. Simple use
Use tuples to describe an HTTP error message
Print (error.0) print(error.1) print(error.1)Copy the code
ErrorCode: "Not Found" print(error.errorCode) print(error.errorinfo)Copy the code
Let (errorCode, errorInfo) = (404, "Not Found") print(errorCode) print(errorInfo)Copy the code
Combine, disassemble
// let httpError = (404,"NotFound") // let (str1,str2) = httpError print(" first argument is \(str1)") print(" second argument is \(str2)") // let httpStatus = httpError print(str3,_) = httpError print(" str3 is \(str3)") // Let httpStatus = \(httpstatus.status)") print(" des: \(httpstatus.status)") print(" des: \(httpstatus.des)")Copy the code