nonocast/me

Swift 语法

Opened this issue · 0 comments

A Swift Tour — The Swift Programming Language (Swift 5.3)

记录一下比较特别的地方

Structures and Classes

我的理解是功能性为主的采用struct,而业务模型采用class

class User {
  var name: String
  var email: String?

  init(_ name: String) {
    self.name = name
  }

  func hello() {
    print("hello \(name)")
  }
}

User("nonocast").hello()

_表示省略外部参数名,对照User(name: "nonocast")

Functions and Closures

最基本的function

func foo() {
  print("hello world")
}

func bar(age: Int) -> Bool {
  return age > 17
}

print(bar(age: 20))

来看closures

let coo = { print("hello world") }
coo()

let chi = { (name: String) in
  print("hello \(name)")
}
chi("nonocast")

通过关键字closure就可以形成一个trailing closures(尾随闭包)的方式, 实际测试发现closure可以省略,方便代码阅读

这是function的形式

func hello(closure action: () -> Void) {
  action()
}

hello {
  print("hello world")
}

func如果是一个单独表达式时可以省略return

func hello() -> Bool {
  return true
}

print(hello())

这是struct/class的形式

struct Task {
  let action: () -> Void

  func exec() {
    action()
  }
}

let task = Task {
  print("hello world")
}

task.exec()

struct会自动生成init,比如这里就是init(action: () -> Void),如果最后且只有一个closure时,这时就可以利用trailing closure方式将closure挂到action上,class就需要手动声明init, 其实init也是func,一个道理。

class Task {
  var action: () -> Void

  init(action: @escaping () -> Void) {
    self.action = action
  }

  func exec() {
    action()
  }
}

let task = Task {
  print("hello world")
}

task.exec()

关于SwiftUI中的细节可以具体参考:

ViewBuilder

VStack {
    Text("Hello World")
    Text("Hello SwiftUI")
    Text("Hello Friends")
}

// equal
VStack {
    return ViewBuilder.builcblock(
        Text("Hello World"), 
        Text("Hello SwiftUI"),
        Text("Hello Friends")
    )
}

关于some的用法: