iOS development from scratch: 00 | Swift basic syntax

Posted by ziv on Fri, 03 Dec 2021 00:06:37 +0100

catalogue

1, Development environment

2, About Swift

(1) Introduction to Swift

(2) Swift properties

(3) Conclusion

3, Swift basic syntax

(1) Programming preparation

(2) Hello,world!

(3) Simple value

1. Variables and constants

2. String

3. Arrays, dictionaries, sets, and tuples

4. Optional type

(4) Control flow

1. Conditional statements

  2. Circular statement

(5) Functions and closures

1. Function

2. Nested functions

3. Input and output parameters

4. Variable parameters

5. Closure

1, Development environment

  • programing language:   Swift (as of September 20, 2021, the latest version is swift 5.5)
  • Development tools:   Xcode editor (available for download in the app store)
  • Operating system:   MacOS (preferably Mojava 2018 or later)
  • Development equipment:   iMac, MacBook, etc. (or virtual machine equipped with MacOS)

Relevant development tools can be found in Swift.org - Download Swift Download

2, About Swift

(1) Introduction to Swift

         Switch is a new programming language released by apple on WWDC in 2014, which can be used to write iOS, OS X and watchOS applications. Swift combines the advantages of C and Objective-C and is not limited by C compatibility.

(2) Swift properties

  1. Security   Swift provides a variety of security measures, such as initialization before value use, automatic memory management, etc.
  2. Rapidity   Swift is designed to replace C-based languages (C, C + + and Objective-C), so for most tasks, swift requires performance comparable to those languages.
  3. expressiveness   Swift combines powerful type inference and pattern matching with modern, lightweight syntax, allowing complex ideas to be expressed in a clear and concise manner. Therefore, the code is not only easier to write, but also easier to read and maintain.
  4. compatibility   Swift can be compatible with Objective-C code. At the same time, swift also inherits the characteristics of C language and Objective-C, which overcomes the compatibility problem of C language.

         reference material: Swift.org - About Swift

         In addition, Swift has the following features:

  1. Swif does not include a macro system, and its protocols and extensions are derived from Objective-C;
  2. Swif uses var to declare variables and let to declare constants;
  3. Swif does not display pointers, but depends on value type / reference type like C# language;
  4. Swif supports local type inference and collation of numeric types, but does not support implicit coercion. All code needs to be converted to explicit types.

         The above contents refer to some views of Rust founder Graydon Hoare on Swift

(3) Conclusion

         Swift is a very modern programming language. If you want to learn swift, you'd better have a certain programming foundation and have a certain understanding of object-oriented programming ideas.

         The author has two most impressive points about Swift——

         First, Swift's powerful character set - swift allows identifiers such as variable names and constant names to use Chinese names, as well as other characters such as expressions (as shown in the figure). Second, swift supports code preview, that is, programmers do not have to wait until the whole program is written before compiling and running the code. Instead, they can view the running results in real time during the process of writing the code. This feature allows us to find some programming errors in time.

         For Swift learning, you can refer to some books and video tutorials, but I think the best way to learn is to check its official document - Swift official Community: Swift.org - Welcome to Swift.org

3, Swift basic syntax

(1) Programming preparation

1. After opening Xcode, you will see the following page

2. Select File - > New - > playground in the upper left corner

3. Select Blank, double-click or click Next

4. Enter the file name and select the file path

Then you can start your Swift journey!  

(2) Hello,world!

         The quickest way to get started with a language is to write a Hello,world! Program, in Swift, this only needs one statement to complete

print("Hello, world!")

Click the icon marked by the red arrow to run. The first run may be slow. Just wait patiently

Unlike C, C + + and other programming languages, which require statements to end with ";", Swift's statements do not need to end with ";". Swift's statements can be divided into simple statements and control flow statements, and each simple statement occupies one line.

(3) Simple value

1. Variables and constants

         Swift uses var to declare variables and let to declare variables.

var aVariable = 65	//Variable declaration
aVariable = 53
let aConstant = 36	//Constant declaration 

         Note that when creating variables and constants, we don't indicate their specific types, but that doesn't mean they don't have types. In the above example, the variable aVariable and the constant aConstant are both integer types because their initial values are integer types.

         Variables and constants in Swift have types, and their types must be the same as the types of values to be assigned to them. The compiler only allows variables or constants to be initialized without always explicitly writing their types, but provides a value for the compiler to infer their types.

         We can also explicitly specify the types of variables and constants:

var aVariable: Int = 65	//Int type variable declaration
aVariable = 53
let aConstant: Float= 36	//Float type constant declaration

The basic data types of Swift include Int, Float, Double, bool (value range: true/false), Character, String, etc.

Swift requires spaces at both ends of a binary operator. In addition, considering the unity of code style, it is better to have spaces at both ends of the assignment number.

2. String

         Swift defines the String type as String         

let label: String = "The width is "	//It can be written as let label = "The width is"
let width = 94
let widthLabel = label + String(width)

         Note that Swift has no implicit conversion. If you need to convert values to different types, you must use display conversion.

         If you need to include a value in the string, you can use the writing method of \ (expression) in the string to escape the value of the expression in parentheses, for example:

let width = 94
let widthLabel = "The width is \(width)"

         As mentioned earlier, Swift's statement does not end with ";. If a string occupies multiple lines, it needs to be surrounded by three double quotation marks" ". Note that the indentation at the beginning of each reference line should be removed, for example:

let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""

3. Arrays, dictionaries, sets, and tuples

         An array is an ordered sequence of elements and a collection containing the same elements. For example:

//Create array:
var shoppingList = ["catfish", "water", "tulips"]	
/*var shoppingList: [String] = ["catfish", "water", "tulips"]*/
shoppingList[1] = "bottle of water"

         We can use append to add elements to the array, and the array will grow automatically, for example:

shoppingList.append("blue paint")

         A dictionary can be understood as a key value pair, and its definition (value) can be found through a specific word (key).

//Create Dictionary:
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

         If you want to create an empty array or empty dictionary, you need to write it as follows:

let shoppingList: [String] = []
let occupations: [String: Float] = [:]

         Set is a whole composed of a group of disordered and non repeated elements of the same type, which is similar to the concept of set in mathematics.

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

         Tuples are collections that can be composed of elements of different types, such as:

var aturple = (18 , 175 , 60.5 , "healthy" , true)

4. Optional type

         The Optional type is a unique data type of Swift. The value of the Optional type may be a value of a certain type or nil (indicating no value).

         For the definition of optional types, add "?" after the type:

var str: String?

          Optional types must be unpacked when used. The following three ways to use optional are provided:

        1) Implicit unpacking

         Use "!" when defining an optional type, and there is no need to force unpacking when making the optional type later

let x : String! = "Hello"
let y = x

        2) Forced unpacking

         When using optional type variables, add "!" after them. If you use illegal variables, the compiler will report an error.

let x : String? = "hello"
let y = x!

         3) If let optional binding

         Use if let temporary constant = optional type to judge whether the optional type contains a value. If it does, assign the value to the temporary constant. Otherwise (when the optional type is nil), the if statement is judged to be false.

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

(4) Control flow

1. Conditional statements

         if branch statement:

if score > 50 {
	teamScore += 3
} else {
	teamScore += 1
}

          switch branch statement:  

var 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.")
}
// Prints "Is it a spicy red pepper?"

  2. Circular statement

          for loop:

var total = 0
for i in 0..<4 {
    total += i
}
print(total)
// Prints "6"
//0.. < = semi closed interval [0,4], 0... 4 = closed interval [0,4]

         If you do not need the value of each item in the interval sequence, you can use the underscore "" instead of the variable name:

let base = 3 ,power = 10 
var answer = 1 
for _ in 1...power { 
answer *= base 
}

        Take the value in the array:

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

         Take the value in the dictionary:

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 (_, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)
// Prints "25"

         while loop:

var n = 2
while n < 100 {
    n *= 2
}
print(n)
// Prints "128"

         While repeat loop (until the loop body executes at least once):

var m = 2
repeat {
    m *= 2
} while m < 100
print(m)
// Prints "128"

(5) Functions and closures

1. Function

         Format of function declaration:

         func function name (parameter name 1: type, parameter name 2: type,...) - > return type {}

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
//person and day are parameter labels and parameter names

          By default, a function uses its parameter name as its parameter label. If the parameter label is different from the parameter name, you need to write the custom parameter label before the parameter name when defining the function, or write to indicate that the parameter label is not used (when calling the function).

func greet(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")

         If the function has multiple return values, tuples can be used as the return 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)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
// Prints "120"
print(statistics.2)
// Prints "120"

2. Nested functions

         Swift's functions can be nested, and nested functions can access variables declared in external functions. We can use nested functions to organize code in long or complex functions.

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

         The return value of one function can be another function:

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

         The parameter of one function can be 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(list: numbers, condition: lessThanTen)

3. Input and output parameters

         In general, it is not allowed to modify the value of the function parameter. Trying to change the parameter value in the function body will cause a compilation error.

         If you want to modify the value of the parameter, you need to use the inout keyword when defining the function; when calling the function, add "&" before the parameter name

func swap(first a : inout Int, second b : inout Int)
{ 
 let temp = a 
 a = b 
 b = temp 
} 
var x = 10,y = 20 
swap (first: &x, second: &y) 
print(x,y)

4. Variable parameters

         A variable parameter can accept 0 or more values. You need to add "..." after the type when defining the parameter of the function

func arithmeticMean(_ numbers: Double...) -> Double { 
 var total: Double = 0 
 for number in numbers { 
 total += number 
 } 
 return total / Double(numbers.count) 
} 
arithmeticMean(1, 2, 3, 4, 5) 
// returns 3.0
arithmeticMean(3, 8.25, 18.75) 
// returns 10.0

5. Closure

         Function is actually a special case of closure: code blocks that can be called later.

         Closures are self-contained function blocks that can be passed and used in code. Global and nested functions are actually special closures. Closures take one of the following three forms:

  •          A global function is a closure that has a name but does not capture any value;
    •          A nested function is a closure that has a name and can capture the value in its closed function field;
      •          A closure expression is an unnamed closure written using lightweight syntax that captures the value of a variable or constant in its context.

         Format of closure expression:

         {(parameter) - > return type in

                 statement

        }

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

Topics: Swift iOS xcode