Basic features
-
About data types
Swift is a strong data type. Constants and variables must be declared before they are used and their types must be clear. Data of different types cannot be calculated, or explicit conversion is required, and constants and variables cannot be exchanged.
Var red, green, blue: Double // random number let ranInt = Int. Random (in: 0.. <5) let ranFloat = Float. Random (in: 0.1.. <3.2) let ranBool = Bool. Random ()Copy the code
-
Comments Multiline comments for Swift can be nested within other multiline comments
/* This is the beginning of the first multi-line comment /* This is the second nested multi-line comment */ This is the end of the first multi-line comment */Copy the code
-
A semicolon
Swift doesn’t force you to use a semicolon (;) at the end of every statement. However, if multiple independent statements are written on the same line, a semicolon must be used
-
Integer An integer is a number that has no fractional part, such as 42 and -23. Integers can be signed (positive, negative, zero) or unsigned (positive, zero). For example, the 8-bit unsigned integer type is UInt8 and the 32-bit signed integer type is Int32
In general, you don’t need to specify the length of an integer. Swift provides a special integer type Int that is the same length as the native word on the current platform: on 32-bit platforms, Int and Int32 are the same length, and on 64-bit platforms, Int and Int64 are the same length.(UInt is similar.)
Let minValue = uint8. min // minValue = 0, is the UInt8 type let maxValue = uint8. Max // maxValue is 255, is the UInt8 typeCopy the code
-
Floating point Numbers
Floating point numbers are numbers with a fractional part, and float numbers infer to Double by default
Swift provides two types of signed floating point numbers:
Double represents a 64-bit floating-point number with a high degree of accuracy of at least 15 digits
Float represents a 32-bit floating point number with only six digits
Let integerPi = Int(PI) //integerPi will be truncated when converted to Int; 4.75 would become 4, and -3.9 would become -3Copy the code
Note: Combining numeric class constants and variables is different from combining numeric class literals. Literal 3 can be added directly to literal 0.14159, because numeric literals themselves have no explicit type. Their types are only inferred if the compiler needs to require a value
-
Type the alias
A type aliases defines another name for an existing type. You can define type aliases using the TypeAlias keyword
typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min Copy the code
-
Boolean Swift has a basic Boolean type called Bool.
Boolean values refer to logical values because they can only be true or false. Swift has two Boolean constants, true and false. Swift’s type-safety mechanism will report an error if you use a non-Boolean value where you want to use a Bool. The following example reports a compile-time error:
Var isSwift = true isswift.toggle ()Copy the code
-
tuples
A tuple is a data structure, similar to an array or dictionary, used to define a set of data
Tuples are not suitable for creating complex data structures
let err = (404,"Not Found") print(err.0) print(err.1) let error = (errCode:404,errInfo:"Mot Found") print(error.errCode) Print (err.errinfo) // The contents of a tuple decompose into separate constants and variables StatusMessage) = err print("The status code is \(statusCode)") Let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)")Copy the code
-
Optional type Optionals
Optionals handle the possibility that a value may be missing. The optionals represent two possibilities: either there is a value, which you can access by resolving the optional type, or there is no value at all.
``` var str0:Optional<String> = nil var str1:String? Var str2: String = nil let possibleNumber = "123" let convertedNumber = Int(possibleNumber) // convertedNumber is presumed to be of type "Int? , or type "optional Int"Copy the code
Note: Nil for Swift is not the same as nil in Objective-C. In Objective-C, nil is a pointer to an object that doesn’t exist. In Swift, nil is not a pointer — it is a definite value used to indicate that a value is missing. Any type of optional state can be set to nil, not just object types.
-
Unpack the
Use! To retrieve an optional value that does not exist causes a runtime error. Use! Make sure that the optional contains a non-nil value before forcing a value to be parsed.
var str1:String? = nil; Str1 = "hello" print(str1) // Print: Optional("hello") // If the optional type is nil, it will unpack if str1! = nil{ print(str1!) }Copy the code
-
Optional binding
An optional binding determines whether the optional type contains a value and assigns the value to a temporary constant or variable if it does. Optional bindings can be used in if and while statements, which can be used not only to determine whether an optional type has a value, but also to assign the value of the optional type to a constant or variable.
// Include multiple optional bindings or Boolean conditions in an if statement, as long as they are separated by commas. // If any of the optional bindings are nil, or if any of the Boolean conditions are false, then the entire if condition is false. var a:Int? a = 4 var b:Int? b = 42 print(b) if let firstNumber = a, let secondNumber = b, firstNumber < secondNumber && secondNumber < 100 { print("\(firstNumber) < \(secondNumber) < 100") }Copy the code
Basic operator
Swift supports most of the standard C operators and has made some improvements to reduce common coding errors. For example, the assignment operator (=) no longer returns a value, thus eliminating the error of writing the judgment operator (==) as an assignment. It also provides interval operators that C does not have, such as a.. < b or a… B, this allows us to express values over an interval
-
Null conjunction operator?? The optional type A is nullified and unpacked if it contains a value, otherwise a default value b is returned.
The expression a must be of type Optional. The type of the default value B must be the same as the type of the value a stores.
let defaultColorName = "red" var userDefinedColorName: String? // Default is nil var colorNameToUse = userDefinedColorName?? defaultColorNameCopy the code
-
Interval operators Closed interval operators (a… B) Define an interval semi-open interval operator that contains all values from a to B, including a and b. <b) define an interval from A to B but not including b
Strings and characters
Note that Swift’s String type Bridges seamlessly with the Foundation NSString class. Foundation also extends String to access methods defined in the NSString type. That means that when you call those NSString methods, you don’t have to do any type casting.
0. Strings are value types
In Swift, String is a value type. If you create a new string, the value is copied when it is constant, variable assignment, or passed in a function/method. In either case, a new copy of an existing string value is created and passed or assigned to that copy instead of the original string.
1. String traversal
Var emptyString = "" // emptyString literal var anotherEmptyString = String() // initializing method var STR = "hello" // literal for c in STR { print(c) }Copy the code
2. String concatenation
let str0 = "w"
let str1 = "p"
let str2 = str0 + str1 + "f"
print(str2)
Copy the code
3. String formatting
let age = 18;
var result = "my age is \(age)"
print(result)
result = String(format: "my age is %ld", age)
print(result);
Copy the code
4. Long string
Let STR = """ hello w hello p hello f """ print(STR)Copy the code
5. String access
The string length count attribute does not always return the same number of characters as the LENGTH attribute of an NSString that contains the same characters. The LENGTH attribute of NSString is a hexadecimal code unit number represented in UTF-16, rather than a Unicode extendable character cluster.
Each String value has an associated index type, String.index, which corresponds to the position of each Character in the String. Different characters may occupy different amounts of memory space, so to know where Character is located, you must traverse each Unicode scalar from the beginning of the String to the end. Therefore, Swift strings cannot be indexed by integers.
The startIndex property retrieves the index of the first Character of a String. The endIndex property retrieves the index of the position after the last Character. Therefore, the endIndex attribute cannot be used as a valid index for a string. If String is empty, startIndex and endIndex are equal.
let greeting = "Guten Tag!"
greeting[greeting.startIndex] // G
greeting[greeting.index(before: greeting.endIndex)] // !
greeting[greeting.index(after: greeting.startIndex)] // u
let index = greeting.index(greeting.startIndex, offsetBy: 7) // a
greeting[index]
Copy the code
The indices property creates a Range with all indexes
For index in greeting. Indices {print("\(greeting[index]) ", terminator: "")}Copy the code
6. Insert and delete
welcome.insert("!" , at: welcome.endIndex) // "hello!" welcome.insert(contentsOf:" there", at: welcome.index(before: welcome.endIndex)) //"hello there!" welcome.remove(at: welcome.index(before: welcome.endIndex)) //"hello there" let range = welcome.index(welcome.endIndex, offsetBy: -3).. < welcome.endIndex welcome.removeSubrange(range)Copy the code
Array set dictionary
Use square brackets [] to create arrays or dictionaries or collections, and use subscripts or keys to access elements
An array of
Arrays can be objects or underlying data types, and arrays use ordered lists to store multiple values of the same type.
Var stands for mutable array let table immutable array
let arr0: Array<Any> = ["wp",18] var arr1 = ["w","p","f"] var arr2 = [Double](repeating: 3, count: [3,3,3] var arr3: [Dounble] = [1.0,2.0] var arr4 = arr2 + arr3 var arr = [String]() var dic = [Strig: Float](Copy the code
1. Array access
Var arr: [Any] = [" w ", "p", "f"] / / the element number print (arr. Count) / / to empty the if arr. IsEmpty {print (" empty ")} else {print (" not empty ")} / / arr increase elements Insert ("Speaker", at: 0) arr. Insert ("Speaker", at: 0) arr. Remove (at: 0) arr.removeFirst() arr.removelast () arr.removeAll() arr.reverse()Copy the code
2. Array traversal
var arr:[Any] = ["w","p","f"] for item in arr { print(item); } for (index,value) in arr.enumerated() { print(index,value) } for item in 0... 1 { print(item) }Copy the code
A collection of
Collections are used to store values of the same type in an undefined order. You can use collections instead of arrays when the order of collection elements is not important or when you want to ensure that each element appears only once.
1. Initialize the collection
var letters = Set<Character>()
letters.insert("a")
letters = []
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
Copy the code
2. Access and modify
// Void if favoriteGenres. IsEmpty {} else {} // Insert favoriteGenres. Insert ("Jazz") // Delete it and return its value if it is an element of the set. Returns nil. If let removedGenre = favoriteGenres. Remove ("Rock") {} else {} // Convert to array favoriteGenres. Sorted ()Copy the code
The dictionary
A dictionary is an unordered collection that stores the relationships between key-value pairs. All the key values need to be of the same type, and all the values need to be of the same type.
1. Dictionary declaration and initialization
var dic0:[Int:String] = [1:"w",2:"p"] var dic1:[String:Any] = [String:Any]() var dic2:[String : Any] = ["name":"wpf","age":18] var dic3:Dictionary<key value> = [] var p:[NSString:Any] = [" name ":" zhange ", "age" : 18, "sex", "male"] p.r emoveValue (forKey: "name") print (p)Copy the code
2. Traversal
for item in dic {
print(item)
}
for key in dic.keys {
print(key)
}
for value in dic.values {
print(value)
}
for (key,value) in dic {
print(key)
print(value)
}
Copy the code
The control flow
Use if and switch for conditional operations, and for-in, while, and repeat-while for loops
() can not be followed after switch, case can not be followed by break, default not through; But a break can end early
If case penetration is required, the keyword fallthrough can be used
Swift supports multiple data types
Let sex = 0 switch sex {case 0: print(" male ") case 1: print(" female ") default: print(" other ")}Copy the code
Let sex = 0 switch sex {case 0: fallthrough case 1: print(" normal ") default: print(" other ")}Copy the code
// float let f = 3.14 switch f {case 3.14: print("π") default: Print (not "PI")} / / string let opration = "+" switch opration {case "+" : print (" + ") case "-" : print (" - ") case "*" : Print ("*") case "/": print("/") default: break} <60: print(" f ") case 60.. <80: print(" pass ") case 80.. <90: print(" good ") case 90.. <100: print(" excellent ") default: print("满分")} Character = "a" switch anotherCharacter { case "a", "A": print("The letter A") default: print("Not the letter A") }Copy the code
If you do not need the value of each item in the interval sequence, you can omit this value by using the underscore _ instead of the variable name
let base = 3 let power = 10 var answer = 1 for _ in 1... power { answer *= base }Copy the code
Switches can also match tuples
let somePoint = (1, 1) switch somePoint { case (0, 0): print("\(somePoint) is at the origin") case (_, 0): print("\(somePoint) is on the x-axis") case (0, _): print("\(somePoint) is on the y-axis") case (-2... 2, 2... 2): print("\(somePoint) is inside the box") default: print("\(somePoint) is outside of the box") }Copy the code
Case branches allow matching values to be declared as temporary constants or variables and used inside the case branch because the matched value is inside the case branch and bound to a temporary constant or variable
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
Copy the code
The pattern of the case branch can use the WHERE statement to determine additional conditions
let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: Print (" (, (x), and (y)) is on the line = = x - y ") case let (x, y) : print (" (, (x), and (y)) is just some arbitrary point ")} / / outputCopy the code
function
Func gotest0() {print(#function)} func gotest1() -> Void {print(#function)} Func gotest2() -> String {return String(format: Func gotest3(name:String,age:Int){print(#function)} Func gotest4(sex:String) -> String {return sex}Copy the code
1. Default parameters
func add(a:Int,b:Int = 20) -> Int {
return a + b
}
print(add(a: 1))
print(add(a: 1, b: 2))
Copy the code
2. Variable parameters
The number of arguments can be variable (of the same type), which is essentially an array argument
func mAdd(a:Int...) -> Int {var temp = 0 for n in a {temp += n} return temp} mAdd(a: 1,2,3)Copy the code
3. Reference types
By default, all parameters are passed by value, and inout is passed by address if external variables need to be changed
func swap(a : inout Int, b : inout Int) {
let temp = a
a = b
b = temp
}
var a = 10
var b = 20
swap(a: &a, b: &b)
print("a:\(a), b:\(b)")
Copy the code
closure
Closure is a special function // unfinished
Copy the code