This article is divided into three parts:
One, the Struct mutable method Two, the plural group (Tuple) use three, the autoclosure use four, Optional Chain use
Mutable method of Struct
Directly on the code:
struct User { var weight:int var height:int // will error left side of mutating operator isn ' t mu Table: ' Self ' is immutable // because the Struct-out variable is immutable, you have to add a keyword when you want to use a method to change the value in a variable mutating mutating func gainweight (newweight:int) { + = newweight117 178 ) newuser.gainweight (ten)
Operation Result:
Second, multivariate group (tuple)
Multi-Group is a new feature of Swift, the common programmer is to define a temporary variable to save the need to exchange the value, now we can use the Multi-group attribute without extra space to directly exchange A and B values
Func swapme<t>(inout a:t, inout b:t) { =56Swapme (&a, B: & Amp b) Print (A, B) //Output result is 6 5
Third, the basic use of autoclosure
//without the use of autoclosureFunc logiftrue (predicate: ()Bool) { ifpredicate () {print ("True") }}//The first method of invocationlogiftrue {(), Boolinch return true}//The second method of invocationLogiftrue ({return 2>1})//The third method of invocationLogiftrue ({2>1})//Fourth method of invocationlogiftrue{2>1}//using AutoclosureFunc logiftrue (@autoclosure predicate: ()Bool) { ifpredicate () {print ("True") } Else{print ("False") }}//Invocation ModeLogiftrue (2>1) Logiftrue (1>2)
iv. use of Optional Chain
class Toy {Let name:string init (name:string) { = name }}class Pet { var toy:toy? }class child { var pet:pet? "" == Child ()
The last access here is name, and in the definition of Toy, name is defined as a string rather than a string? , but the toyname we get is actually a String type. Is this because in Optional Chaining we are in any one? Can meet nil and return early, this time of course you can only get nil.
Let Toyname = Xiaoming.pet?. Toy? . Name // so in actual development, we usually use Optional Binding to directly value: if let Toyname = Xiaoming.pet?. Toy? . Name { /// then Toyname is a string instead of a string? }extension Toy { func play () { pri NT (" Play Toys ~ ~") in child.pet?. Toy? . Play ()}
Swift development fifth-four points of knowledge (Struct mutable method &tuple&autoclosure&optional Chain)