IOS development language Swift getting started

Source: Internet
Author: User

IOS development language Swift getting started

Generally, the first program in the programming language tutorial should print "Hello,> world" on the screen ". In> Swift>, you can use a line of code:

println("Hello, world");

If you have written> C> or> Objective-C> code, you should be familiar with this form-in Swift, this line of code is a complete program. You do not need to import a separate library for input/output or string processing. The code in the global scope is automatically used as the entry point of the program, so you do not need the main function. You do not need to end each statement with a semicolon.
This tutorial uses a series of programming examples to give you a preliminary understanding of Swift>, don't worry if you have anything you don't understand-any content introduced in this chapter will be detailed in the following sections.
Note:

To get the best experience, use the code preview function in Xcode. The Code preview function allows you to edit the code and view the running result in real time.
Simple Value

Use let to declare constants, and use var to declare variables. The value of a constant does not need to be obtained during compilation, but you can only assign values to it once. That is to say, you can use constants to represent such a value: you only need to decide once, but you need to use it many times.
  

var myVariable = 42myVariable = 50let myConstant = 42

Constants or variables must be of the same type as the values you assign them. However, the declared type is optional. If the declared value is assigned at the same time, the compiler will automatically infer the type. In the preceding example, the compiler deduced that myVariable is an integer because its initial value is an integer.
If the initial value does not provide enough information (or there is no initial value), declare the type after the variable and separate it with a colon.
  

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

Exercise:
Create a constant, explicitly specify the Float type and specify the initial value as 4.

The value is never implicitly converted to another type. If you want to convert a value to another type, convert it explicitly.
  

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

 Exercise:
Delete the String in the last row. What is the error message?

There is a simpler way to convert a value into a string: Write the value into parentheses, and write a backslash before the parentheses. For example:
  

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

Exercise:
Use () to convert a floating point computation into a string and add a person's name to greet him.

Use square brackets [] to create arrays and dictionaries, and use subscript or key to access elements.
  

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

To create an empty array or dictionary, use the initialization syntax.

let emptyArray = String[]()let emptyDictionary = Dictionary
  
   ()
  

If the type information can be inferred, you can use [] and [:] to create an empty array and an empty dictionary-just like when you declare a variable or pass a parameter to a function.
  

ShoppingList = [] // go shopping and buy something
Control Flow

Use if and switch for conditional operations, and use for-in, for, while, and do-while for loop. The wrap condition and loop variable parentheses can be omitted, but the statement body braces are required.

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

In the if statement, the condition must be a Boolean expression -- this means that the condition is like if score {... } Such code will report an error and will not be implicitly compared with 0.
You can use if and let together to process missing values. The values of some variables are optional. An optional value may be a specific value or nil, indicating that the value is missing. It is optional to add a question mark after the type to mark the value of this variable.
  

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

Exercise:
Change optionalName to nil. What will greeting be? Add an else statement and assign a different value to greeting when optionalName is nil.

If the optional value of the variable is nil, the condition is false, and the code in braces is skipped. If it is not nil, the value is assigned to the constant after let, so that this value can be used in the code block.
Switch supports any type of data and various comparison operations-not only integers and test equality.
  

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

Exercise:
Delete the default statement to see if any errors occur?

After running the matching clause in the switch, the program exits the switch statement and does not continue to run downward. Therefore, you do not need to write break at the end of each clause.
You can use for-in to traverse the dictionary. Two variables are required to represent each key-value pair.
  

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

 Exercise:
Add another variable to record which type of number is the largest.
Use while to run a piece of code repeatedly until the conditions are not met. Loop conditions can start or end with them.
  

var n = 2while n < 100 {    n = n * 2}nvar m = 2do {    m = m * 2} while m < 100m

You can use... to represent the range in the loop, or you can use the traditional method. The two are equivalent:

var firstForLoop = 0for i in 0..3 {    firstForLoop += i}firstForLoopvar secondForLoop = 0for var i = 0; i < 3; ++i {    secondForLoop += 1}secondForLoop

The range created using... does not contain the upper limit. If you want to include it, use...
  

Functions and closures

Use func to declare a function and call the function by name and parameter. Use-> to specify the function return value.

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

Exercise:
Delete the day parameter and add a parameter to indicate what lunch is taking today.
Returns multiple values using a single tuple.

func getGasPrices() -> (Double, Double, Double) {    return (3.59, 3.69, 3.79)}getGasPrices()

The number of parameters of a function is variable, and an array is used to obtain them:

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

Exercise:
Write a function that calculates the average value of a parameter.
Functions can be nested. Nested functions can access the variables of external functions. You can use nested functions to reconstruct a function that is too long or too complex.

func returnFifteen() -> Int {    var y = 10    func add() {        y += 5    }    add()    return y}returnFifteen()

A function is a first-class citizen, which means that a function can be returned as another function.

func makeIncrementer() -> (Int -> Int) {    func addOne(number: Int) -> Int {        return 1 + number    }    return addOne}var increment = makeIncrementer()increment(7)

A function can also be used as a parameter to pass in another function.

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}var numbers = [20, 19, 7, 12]hasAnyMatches(numbers, lessThanTen)

A function is actually a special closure. You can use {} to create an anonymous closure. Use in to separate the parameter and return value type declarations from the closure function bodies.

numbers.map({    (number: Int) -> Int in    let result = 3 * number    return result    })

Exercise:
Override the closure and return> 0 for all odd values.
There are many ways to create a closure. If the type of a closure is known, for example, as a callback function, you can ignore the type and return value of the parameter. The closure of a single statement returns the value of the statement as a result.
You reference a parameter through the parameter location rather than the parameter name-this method is very useful in very short closures. When a closure is passed to a function as the last parameter, it can be directly followed by brackets.

sort([1, 5, 3, 12, 2]) { $0 > $1 }
Objects and Classes

Use the class and class Name to create a class. The declaration of attributes in a class is the same as that of constants and variables. The only difference is that their context is a class. Similarly, methods and function declarations are the same.

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

Exercise:

Use let to add a constant attribute, and then add a method to receive a parameter.
To create an instance of a class, add brackets behind the class name. Use the dot syntax to access instance attributes and methods.

Note that self is used to differentiate instance variables. When you create an instance, you can pass in parameters of the constructor to the class just like passing in function parameters. Each attribute must be assigned a value-whether through declaration (like numberOfSides) or through the constructor (like name ).
If you need to clear the object before deleting it, use deinit to create a destructor.
The subclass definition method is to add the parent class name after their class names and use colons to separate them. You do not need a standard root class when creating a class, so you can ignore the parent class.
Subclass if you want to override the method of the parent class, you need to use the override flag -- If override is not added, the compiler will report an error. The compiler also checks whether the methods marked by override are indeed in the parent class.

class Square: NamedShape {    var sideLength: Double    init(sideLength: Double, name: String) {        self.sideLength = sideLength        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()

Exercise:
Create another sub-class Circle of NamedShape. The constructor receives two parameters. One is the radius and the other is the name, which implements the area and describe methods.
The attributes include> getter> and> setter>.

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

In perimeter> setter>, the new value is named newValue. You can explicitly set a name after set.
Note that the constructor of the EquilateralTriangle class executes three steps:
1.> set the attribute value declared by the subclass
2.> call the constructor of the parent class
3.> change the attribute value defined by the parent class. Other work, such as calling methods, getters, and setters, can also be completed at this stage.
If you do not need to calculate attributes, but you need to run some code before setting a new value, use willSet and didSet.
For example, the following class ensures that the side length of a triangle is always the same as that of a square.

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")triangleAndSquare.square.sideLengthtriangleAndSquare.triangle.sideLengthtriangleAndSquare.square = Square(sideLength: 50, name: "larger square")triangleAndSquare.triangle.sideLength

There is an important difference between a method in a class and a general function. The parameter name of a function is used only within the function, however, the method parameter name must be explicitly described (except the first parameter) during the call ). By default, the parameter name of a method is the same as its internal name, but you can also define the second name, which is used inside the method.

class Counter {    var count: Int = 0    func incrementBy(amount: Int, numberOfTimes times: Int) {        count += amount * times    }}var counter = Counter()counter.incrementBy(2, numberOfTimes: 7)

When processing optional values of variables, you can add them before operations (such as methods, attributes, and subscripts? . If? The previous value is nil ,? All subsequent things are ignored, and the entire expression returns nil. Otherwise ,? All subsequent things will be run. In both cases, the value of the entire expression is also an optional value.

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")let sideLength = optionalSquare?.sideLength
Enumeration and struct

Use enum to create an enumeration. Like all other Naming types, enumeration can contain methods.

enum Rank: Int {    case Ace = 1    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten    case Jack, Queen, King    func simpleDescription() -> String {        switch self {        case .Ace:            return "ace"        case .Jack:            return "jack"        case .Queen:            return "queen"        case .King:            return "king"        default:            return String(self.toRaw())        }    }}let ace = Rank.Acelet aceRawValue = ace.toRaw()

  Exercise:
Write a function and compare two Rank values by comparing their original values.
In the preceding example, the type of the enumerated original value is Int, so you only need to set the first original value. The remaining original values are assigned values in sequence. You can also use a string or floating point number as the original enumerated value.
Use the toRaw and fromRaw functions to convert the original and enumerated values.

if let convertedRank = Rank.fromRaw(3) {    let threeDescription = convertedRank.simpleDescription()}

The enumerated member value is an actual value and is not another expression of the original value. In fact, if the original value is meaningless, you do not need to set it.

enum Suit {    case Spades, Hearts, Diamonds, Clubs    func simpleDescription() -> String {        switch self {        case .Spades:            return "spades"        case .Hearts:            return "hearts"        case .Diamonds:            return "diamonds"        case .Clubs:            return "clubs"        }    }}let hearts = Suit.Heartslet heartsDescription = hearts.simpleDescription()

  Exercise:
Add a color method to Suit, return "black" to spades and clubs, and "red" to hearts and diamonds ".
Note that there are two ways to reference a Hearts Member: when assigning a value to a hearts constant, the enumerated member Suit. Hearts needs to be referenced by the full name, because the constant does not explicitly specify the type. In the switch, enumeration members are abbreviated. . Hearts to reference, because the value of self is already known as a suit. You can use the abbreviation when the variable type is known.
Use struct to create a struct. Struct and class have many similarities, such as methods and constructors. The biggest difference between them is that the struct is to pass the value, and the class is to pass the reference.

struct Card {    var rank: Rank    var suit: Suit    func simpleDescription() -> String {        return "The \(rank.simpleDescription()) of \        (suit.simpleDescription())"    }}let threeOfSpades = Card(rank: .Three, suit: .Spades)let threeOfSpadesDescription = threeOfSpades.simpleDescription()

  Exercise:
Add a method to Card, create a complete playing Card, and match the rank of each Card with suit.
An instance of an enumerated member can have an Instance value. Instances with the same enumerated members can have different values. Enter a value when creating an instance. The instance value is different from the original value: the original value of the enumeration member is the same for all instances, and you set the original value when defining the enumeration.
For example, consider getting the sunrise and sunset time from the server. The server returns normal results or error messages.

enum ServerResponse {    case Result(String, String)    case Error(String)}let success = ServerResponse.Result("6:00 am", "8:09 pm")let failure = ServerResponse.Error("Out of cheese.")switch success {case let .Result(sunrise, sunset):    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."case let .Error(error):    let serverResponse = "Failure...  \(error)"}

  Exercise:
Add the third case to ServerResponse and switc.
Note how to extract sunrise and sunset time from ServerResponse.
Interfaces and extensions
Use protocol to declare an interface.

protocol ExampleProtocol {    var simpleDescription: String { get }    mutating func adjust()}

Class, enumeration, and structure can all implement interfaces.

class SimpleClass: ExampleProtocol {    var simpleDescription: String = "A very simple class."    var anotherProperty: Int = 69105    func adjust() {        simpleDescription += "  Now 100% adjusted."    }}var a = SimpleClass()a.adjust()let aDescription = a.simpleDescriptionstruct SimpleStructure: ExampleProtocol {    var simpleDescription: String = "A simple structure"    mutating func adjust() {        simpleDescription += " (adjusted)"    }}var b = SimpleStructure()b.adjust()let bDescription = b.simpleDescription

  Exercise:
Write an enumeration to implement this interface.
Note that the mutating keyword is used to mark a method that modifies the struct when SimpleStructure is declared. SimpleClass declaration does not need to mark any methods because the methods in the class often modify the class.
Use extension to add functions for existing types, such as adding a calculation attribute method. You can use extensions to add protocols to any type, or even the types you import from external libraries or frameworks.

extension Int: ExampleProtocol {    var simpleDescription: String {    return "The number \(self)"    }    mutating func adjust() {        self += 42    }}7.simpleDescription

  Exercise:
Write an extension for the Double type to add the absoluteValue function.
You can use an interface name like other Naming types. For example, you can create an object set that has different types but implements one interface. When the processing type is the interface value, the method defined outside the interface is unavailable.

let protocolValue: ExampleProtocol = aprotocolValue.simpleDescription// protocolValue.anotherProperty  // Uncomment to see the error

Even if the protocolValue variable runtime type is simpleClass, the compiler regards its type as ExampleProtocol. This means that you cannot call methods or attributes implemented by the class beyond the interfaces implemented by the class.
Generic
Write a name in the angle brackets to create a generic function or type.

func repeat
  
   (item: ItemType, times: Int) -> ItemType[] {    var result = ItemType[]()    for i in 0..times {        result += item    }    return result}repeat("knock", 4)
  

You can also create generic classes, enumerations, and struct.

// Reimplement the Swift standard library's optional typeenum OptionalValue
  
    {    case None    case Some(T)}var possibleInteger: OptionalValue
   
     = .NonepossibleInteger = .Some(100)
   
  

Use the where clause after the type name to specify a list of requirements. For example, to limit the type of a protocol, you must specify the two types to be the same, or a class must have a specific parent class.

func anyCommonElements 
  
    (lhs: T, rhs: U) -> Bool {    for lhsItem in lhs {        for rhsItem in rhs {            if lhsItem == rhsItem {                return true            }        }    }    return false}anyCommonElements([1, 2, 3], [3])
  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.