Swift3 study notes – 0

Welcome to my blog, muhlenXi, which comes from my blog.

Copyright statement: This article is the original article muhlenXi, reproduced please indicate the source, without permission shall not be reproduced


Swift is a new programming language, it can be developed using iOS, macOS, watchOS and tvOS on the platform of App, it is qualified for C and Objective-C language to better the work, Swift uses safe programming mode, it adds some modern features makes programming easier, more flexible and more interesting. Swift popular Cocoa and CocoaTouch framework based on the mature, this is a re definition of how the software development opportunities! Just enjoy it!.

Click on the full text to find out the details.

<! – more –>

The first experience of Swift

Single variable

Print hello on screen, world!
Print ("Hello, world!")
Define a variable and change the value of the variable
Var myVariable = 42 myVariable = 50
Define a constant
Let myConstant = 38

We define constants and variables that can not be declared as a constant or variable data type, the compiler will be based on the initial value you set to guess the type of data.

The declaration of constants with data types is such.

Let myWeight:Double = 54
String type conversion.
Let label = "the width is" width = 94 let widthLabel = label + String (width)

There’s a simpler way.

Let apples = 3 let oranges = let appleSummary = I hava / (apples) let fruitSummary = I have / (apples + oranges) pieces of apples fruit"
Defining an immutable array
Let animals = "monkey", "elephant", "rabbit"
Defining a variable array
Var fruitLists = "Apple Juice", "banana", "pear", "grape" fruitLists[0] = "apple" / / modify the fruitLists.append ("Kiwi") / / fruitLists.remove (at: 4) / / delete

Define an empty array

Let animals = [String] ()
Defining an immutable dictionary
Let wheelsOfCar = ["wheelbarrow": 1, 2: "bicycle", "car": 4]

Define an empty dictionary

Let emptyDictionary = [String: NSInteger] ()
Define a variable dictionary
Var wheelsOfCar = ["wheelbarrow": 1, 2: "bicycle", "car" 4]: wheelsOfCar["tricycle"] = 3 / / add or modify wheelsOfCar.removeValue (forKey: "tricycle") print ("/ / / delete (wheelsOfCar)")

control flow

If – else condition statement
Let scores = [75,43103,87] var count = 0 for score in scores if score > {1} {count = 50; else = 0} {count} print ("score greater than zero subject number: / (count)")

After if or else () can be omitted, but is not omitted!

Optional operation
Let optionalName:String? Var greeting = "three" = "Hello if!" let name = optionalName {greeting = "hello / (name)}else {greeting =" optionalName is nil "/ / when the name for the nil are executed when the print (greeting)}

We can also use the operator to set a default value for the optional value, and when the optional value is nil, the default value is automatically filled!

Let nickName:String = nil defaultName = "Li four" let informalGreeting = "Hi / (nickName? DefaultName)" print (informalGreeting)
Switch – case condition statement
Let vegetable = "potatoes" switch vegetable {case "pepper": Print ("chili" eat more easily get angry. "Case" sweet potato "," potato ": Print (" this vegetable starch content is relatively high). "Case let where x.hasSuffix (" melon "): Print (" / (x) belongs to a kind of gourd ") default: print (" the information on this vegetable is not yet available). "})
Traversing an array or dictionary by for – in
Let [intersetingNumbers = "prime": [2,3,5,7,11,13], "Fibonacci": [1,1,2,3,5,8], "square": [1,4,9,16,25]] var largest = 0 / / find the maximum number of the number of for (_, numbers) in intersetingNumbers number in numbers {for {if number > largest largest = {number}}} print (largest)
For-in can be used to control the number of cycles
/ / full closed interval var sum = 0 for I in 0... 4 {sum = sum + I / / 5 cycles} print (sum) / / half closed interval var sum1 = 0 for I in 0..< sum1 = sum1 + 4 {I} / / 4 cycles of print (sum1)
While cycle and repeat – while cycle
After the implementation of VaR n / / the first judge while n < = 2; n = n * 100 {2} print (n) / / 128 / / the first output after the implementation of VaR m repeat {M = M = 2 * 2}while m < print (m); 100 / 128 output

Functions and closures

Declare a function with func, () is a parameter, -> followed by the type of return value
Func greet (person: String, day: ->); String {return "hello / (person), today is / (day) (String). "}

Function call:

Let str:String = greet ("person: three", "Sunday" / / day:) function print (STR)
Default parameter name is not set

When we declare a function without specifying the parameter name, parameter name defaults to the formal parameter name, of course, we can use the _ to prohibit setting the default parameter name

Func greet (_ person:String, on day:String -> String) {return Hello / (person), today / is (day)} "

Method call is this:

Print (greet ("Tom", on: "Monday")
Use tuples (tuple) to create composite values
Func calculateStatistics (scores:[Int]) -> (min:Int, max:Int, sum:Int) {var min = scores[0] var max = scores[0] var sum = 0 for score in scores if score > {Max} {max = score; else if score < Min Min = {score}} = sum score return (min, Max, sum})

Function call:

Let statistics = calculateStatistics (scores: [5,3100,25,4]) print (min = / (statistics.min)) print (max = / (statistics.max)) print (sum = / (statistics.2))

The number of parameters of the function can also be uncertain

Func sumOf (numbers:Int...) -> Int {var sum = 0 for num in numbers num return sum = {sum}}

This is called:

(print) (sumOf) / 0 print output (sumOf (numbers: 100200,50)) / / output 350
Functions can be nested, nested functions can read or modify the value of the external variable function.
Func (returnFifteen) / / function definition -> Int {var y = 10 func (add) {y} = 5 add (return y);} / / function: Print (returnFifteen ())
The return value of a function can also be a function.
/ / generate a func makeIncrementer (->) increment; ((Int) -> Int) {func addOne (number:Int) -> Int return {number + 1} return addOne;} / / increment = makeIncrementer (let method) print (increment (7))
Function parameters can also be functions.
Func lessThanTen (number:Int) -> Bool return number < {10}; / / check array contains less than 10 elements (list:[Int], func checkArray condition: (Int) -> Bool -> Bool) {for item in list if condition (item) {true}} {return return false}

This is the function call:

Let numbers = [18,9,17,12] RET = checkArray (list: numbers, condition: lessThanTen) print (RET) (let)
The function is a special form of closure, can achieve a closure of the braces, in the closure by in to separate the parameter and return types.
Let numbers = [20,19,7,12] / / array values of elements in double let mappedNumbers = numbers.map ({number in number * 2}) print (mappedNumbers) / / reverse arrangement of elements in the array let sortedNumbers = numbers.sorted{$0 > $1} print (sortedNumbers)

Objects and classes

Use class to create a class, the declaration of the attributes and constants, variables, like the declaration, the method and function of the declaration of the same way.

Init can be generated through a initializer to initialize the object.

Deinit can be used to generate a deinitializer, when the object is released to do some clean-up work.

Class declarations are as follows:

A statement / geometry class Shape {var numberOfSides = 0 / / var number: String / / name boundary geometry name init (name:String) {self.name} = name / simpleDescription (->) a brief description of func; String {return (name) / "this is called geometry / (numberOfSides). Edge"}}

Class object generation:

Let shape = Shape.init (name: / shape.numberOfSides = 7 ") print ((shape.simpleDescription))
Class inheritance

If the class is inherited a parent class, that class must use mechanical time: + to indicate its superclass name inherited from what kind of. When there is no parent class, you can omit write.

When the class to override the parent class method, to add keywords override subclass method

Declare a Square class that inherits Shape

Square class Square: Shape {var / / sideLength:Double / / init length (sideLength:Double, name:String) {self.sideLength = sideLength (super.init name: name) numberOfSides = 4 override func simpleDescription (->)} String {return; "this is called / geometry (name) / (numberOfSides) edge length (sideLength / cm) func area / /"} area calculation (->); Double return {sideLength sideLength}} *

Subclass object creation:

Let square = Square.init (sideLength: 4, name: "square") print ("area is: / (square.area))" print (square.simpleDescription) ()
Class properties, you can also generate their own getter and setter methods:
Class EquialateralTriangle: Shape / equilateral triangle {var sideLenth Double = 0 init (sideLength:Double, name:String) {self.sideLenth = sideLength (super.init name: name) numberOfSides = 3} perimeter:Double {set {/ / perimeter var sideLenth = newValue / 3} get {return}} * 3 sideLenth override func simpleDescription (-> String) {return "this is a side length of the equilateral triangle / (sideLenth)}}"

Creation of equilateral triangle objects:

Let triangle = EquialateralTriangle.init (sideLength: 5, name: "triangle") print ("/ / get the perimeter of the perimeter is: / (triangle.perimeter) triangle.perimeter = 12") / / get modified perimeter after the side length of print ("length: / (triangle.sideLenth)" (triangle.simpleDescription) (print))

Enumerations and structures

Enum to declare an enumeration, enumeration can also be related to the function

The first enumeration value is 0 by default, and we can also specify the first enumeration value for the value we want.


Enum Direction: NSInteger {case up = 1, down, left, right func description (->); String self case.Up: {switch {return "to" case.Down: return "case.Left: return" down "to the left" case.Right: return "right"}}}

Call as follows:

Let direc = Direction.down print (direc) print (direc.rawValue) print (direc.description) ()

We can also initialize an enumeration option by rawValue to get a possible value.

Let direc = Direction (rawValue: 2) print (direc!.description)

The options in the enumeration can also be associated with different constant values, and when we create an instance of an enumeration, we can initialize different constants.

Enum ServerResponse {case result (String, String) case failure (String)}
Struct to declare a structure, the enumeration can also be associated with the function


Struct Rectangle var {/ / rectangular type origin:CGPoint var width:Float var height:Float func area (-> String) {let area = width * height / return (area) func perimeter (->)} "; Float {return (width + height) * 2}}

Simple application

Let myRectangle = Rectangle (origin: CGPoint.init (x: 0, y: 0), width:, height:, 6) print ("perimeter: / (myRectangle.perimeter))" print "(area: / (myRectangle.area)) ()

Class extensions

Use protocol to declare an agreement.
Protocol TestProtocol {var {get} mutating adjust func ()}

Classes, enumerations, and structures can follow the protocol

Class TestClass: TestProtocol {var value:Int var = 108 simpleDescription: String = "this is a test class" (func adjust) {simpleDescription.append ("+ test value is / (value) struct TestStruct:TestProtocol")}} {var simpleDescription: String = "a test structure" mutating func (adjust) {simpleDescription.append ("+ follow the agreement")}}

Simple application

Let test = (TestClass) test.adjust (test.simpleDescription) var = TestStruct () testStruct.adjust () print (print) (testStruct.simpleDescription) (testStruct)
Use extension to declare a class extension, adding a method or value attribute to the existing class.


Extension Int {/ / value profile attribute var "the number return simpleDescription:String {(self)} / / /" 2 mutating func addTwo (increment) {self = self + 2}}

Simple use

Var = num:Int = 8 print (num.simpleDescription) print (num.addTwo) (Num)

Extension can also be used to allow a class or data type to follow an agreement.

Protocol testProtocol var {simpleDescription:String {get} mutating func (adjust) extension Double: testProtocol simpleDescription: {var} String {return "Double / value (self) func (adjust) mutating"} {self}} = 2

Simple application:

Var = pi:Double = 3.14 print (pi.simpleDescription) print (pi.adjust) (PI)

error handling

Declare an error type by following the error protocol Error.

Enum PrinterError:Error {outOfPaper case case onFire} noToner case

Throw to throw errors and use throws to mark a function that can throw an error, when the function throws an error, the function will return immediately, and call the error handling method.

Func (send job:Int, toPrinter printerName:String throws -> String) {if printerName = = "Nerver Has Toner" throw PrinterError.noToner return "} {Job sent}

Use do-catch to handle errors in the do block, the call may throw an error function, the front need to use try to mark, and in the catch block, incorrect default name is error, unless you set an alias.

Do {let = try send (job: 1040, toPrinter: "Nerver Has Toner") print (printerResponse)} catch {print (error)}}

Multiple catch blocks can be used to handle errors in detail

Do {let printerResponse = try send (job: 1040, toPrinter: "Nerver Has Toner") print catch PrinterError.onFire (printerResponse)} {print ("printer overheating, rest for a while and then use the" catch PrinterError.noToner{(print)} "printer ink, please add ink")} catch {print ("out of paper, please add paper")}

Another error is to use try to convert the result to an optional value. If the function throws an error, the error will be discarded and the result will be nil, otherwise the return value is an optional value that contains the result.

Let printerSuccess = try? Send (job: 1884, toPrinter: "Hello world") let printerFailure = try send (job: 1884, toPrinter: "Nerver Has Toner")

The defer code block is used to declare a statement that needs to be executed before the function returns.

Var fridgeIsOpen = false let fridgeContent = "milk", "eggs", "apple"] func fridgeContains (food:String) -> Bool fridgeIsOpen = true {defer} false {fridgeIsOpen = let result = fridgeContent.contains (food) return result}

Simple application

Let RET = fridgeContains (food: "banana") print (RET) print (fridgeIsOpen)

generic paradigm

< name> declare a generic or generic method.
Func makeArray< (repeat item:Item; Item> -> [Item], numberOfItems:Int) {var result = [Item] (for) _ in 0..< numberOfItems result.append (item)} return {result} / / function call print (makeArray (repeat: Apple, numberOfItems: 7))

Functions, classes, enumerations, structures, etc. can also be declared as generic

Enum OptionalValue< Wrapped> case some; case none {(Wrapped)} / / var possibleValue:OptionalValue< Int> simple call;.None = possibleValue =.Some (200) print (possibleValue)

Use where to specify the requirements for a type after the name of the method – for example, the need to implement a protocol that requires the same type of two objects, or both

To determine whether there is a common element of the func / anyCommonElements< T: Sequence, U: Sequence> (lhs: T; _ _, rhs: U -> Bool where T.Iterator.Element:); Equatable, T.Iterator.Element = = U.Iterator.Element {for {for lhsItem in LHS rhsItem in RHS {if lhsItem = = rhsItem {return true}}}} return false

Simple application

Let RET = anyCommonElements ([1,2,3], [5]) print (RET)

Concluding remarks:

Check the official Swift3 documentation here

Thanks for reading, there is nothing wrong with the message to me, to learn together, progress together!