Swift Tour

Original link: http://www.cnblogs.com/xiaoxiaff/p/5380666.html

Set constants used let, set variables var

var myVariable = 42
myVariable = 50
let myConstant = 42

The compiler can infer that the variable type and therefore do not themselves explicitly defined.

If no initial value or information is insufficient to allow the compiler to judge, you can explicitly declare by a colon:

let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

Any type of variable can not implicit conversion, conversion between all variables are explicit:

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

For the String conversion, there is an easier way:

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

Dictionary和List:

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

initialization:

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

If the type is relatively fixed, can be used [] or [:] Create an empty list and Dictionary:

shoppingList = []
occupations = [:]

for if statement:

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

Note that, because there is no implicit conversion, the digital direct comparison condition when error.

However, when the optional variables and let may be used if optional variable exists determines whether or with

var optionalString: String? = "Hello"
print(optionalString == nil)
 
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

For optional variable, may also confer default values ​​??:

let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

It may also be used to let the matching variables:

let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

swift switch statement automatically break.

When using for-in dictionary of traversal, key-value pairs are unordered:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)

while和do-while

var n = 2
while n < 100 {
    n = n * 2
}
print(n)
 
Do you have = 2
repeat {
    m = m * 2
} while m < 100
print(m)

Also be used when the cycle .. <cycle range for:

, total = 0 
for the in  0 .. < 4 {
    total += i
}
print(total)

Use func function declaration, by -> the parameter and return value are separated:

func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", day: "Tuesday")

Function can also pass list, return tuple:

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    my = scores [ 0 ]
    var max = scores[0]
    was some = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    
    return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)

While also variable parameter:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)

Functions can also be nested statement:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)

Function can also be passed as a parameter:

func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
was increment = makeIncrementer ()
increment(7)
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
numbers to a var = [ 20 , 19 , 7 , 12 ]
hasAnyMatches(numbers, condition: lessThanTen)

Class declarations and object declarations:

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

Constructor:

class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

Destructors deinit

When inheritance, methods override the need to explicitly declare:

class Square: NamedShape {
    was sidelengths: Double
    
    init(sideLength: Double, name: String) {
        self.sideLength = sidelengths
        super.init(name: name)
        numberOfSides = 4
    }
    
    func area() ->  Double {
        return sideLength * sideLength
    }
    
    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

Setter and Getter

class EquilateralTriangle: NamedShape {
    was sidelengths: Double = 0.0
    
    init(sideLength: Double, name: String) {
        self.sideLength = sidelengths
        super.init(name: name)
        numberOfSides = 3
    }
    
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sidelengths = NewValue / 3.0
        }
    }
    
    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)."
    }
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)

Here setter pass argument implicitly declared newValue, you can customize the set of variable names in parentheses after the previously declared.

If desired predefined set before or after the operation, and may be used willSet didSet:

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)

At the time of the optional variable operation, if the optional variable is nil, then the statement after? All is not executed, the entire statement is nil.

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
look sidelengths = optionalSquare? .sideLength

Different structure and in that class, structure pass through a reference copy, and class by reference.

 

Reproduced in: https: //www.cnblogs.com/xiaoxiaff/p/5380666.html

Guess you like

Origin blog.csdn.net/weixin_30721899/article/details/94787951