Algorithmic Vision | Learning | Coding

iOS Development 02: Function, Struct & Class

函数[Function]

func functionName(arg1: Type1) -> Type2 {
    ...
    ...
}

闭包[Closure]

跟随闭包[Trailing Closure]

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. You write a trailing closure after the function call’s parentheses, even though the trailing closure is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the first closure as part of the function call. A function call can include multiple trailing closures; however, the first few examples below use a single trailing closure.

func someFunctionThatTakesAClosure(closure: () -> Void) {
    // function body goes here
}

// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure: {
    // closure's body goes here
})

// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
    // trailing closure's body goes here
}

If a function takes multiple closures, you omit the argument label for the first trailing closure and you label the remaining trailing closures.

func loadPicture(from server: Server, completion: (Picture) -> Void, onFailure: () -> Void) {
    if let picture = download("photo.jpg", from: server) {
        completion(picture)
    } else {
        onFailure()
    }
}
// how you call function with multiple closure argument
loadPicture(from: someServer) { picture in
    someView.currentPicture = picture
} onFailure: {
    print("Couldn't download the next picture.")
}

类和结构体对比

struct_vs_class

Structures and classes in Swift have many things in common. Both can:

  • Define properties to store values
  • Define methods to provide functionality
  • Define subscripts to provide access to their values using subscript syntax
  • Define initializers to set up their initial state
  • Be extended to expand their functionality beyond a default implementation
  • Conform to protocols to provide standard functionality of a certain kind

For more information, see Properties, Methods, Subscripts, Initialization, Extensions, and Protocols.

Classes have additional capabilities that structures don’t have:

  • Inheritance enables one class to inherit the characteristics of another.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • De-initializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.

For more information, see Inheritance, Type Casting, Deinitialization, and Automatic Reference Counting.

属性包装器[Property Wrapper]

Property Wrapper为“属性是如何存储(被管理)的”与“属性如何被定义的”这两部分的代码实现提供了一个分隔。属性包装器非常类似Python的装饰器(甚至在语法糖方面都使用@符号)。使用属性包装器时,在定义包装器时编写一次属性管理的代码,然后通过将其应用于多个属性来复用该部分管理代码。