基础语法

语言特点 #

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

The goal of the Swift project is to create the best available language for uses ranging from systems programming, to mobile and desktop apps, scaling up to cloud services. Most importantly, Swift is designed to make writing and maintaining correct programs easier for the developer. To achieve this goal, we believe that the most obvious way to write Swift code must also be:

Safe. The most obvious way to write code should also behave in a safe manner. Undefined behavior is the enemy of safety, and developer mistakes should be caught before software is in production. Opting for safety sometimes means Swift will feel strict, but we believe that clarity saves time in the long run.

Fast. Swift is intended as a replacement for C-based languages (C, C++, and Objective-C). As such, Swift must be comparable to those languages in performance for most tasks. Performance must also be predictable and consistent, not just fast in short bursts that require clean-up later. There are lots of languages with novel features — being fast is rare.

Expressive. Swift benefits from decades of advancement in computer science to offer syntax that is a joy to use, with modern features developers expect. But Swift is never done. We will monitor language advancements and embrace what works, continually evolving to make Swift even better.

数据声明 #

swift 使用 let 来声明常量,使用 var 来声明变量。常量只能赋值一次。

即:let的内存地址不能变,var的内存地址可变。

// 只能赋值一次,再次赋值会报错
let hello = "world"
print(hello)

// hello 可以多次赋值
var hello = "world"
print(hello)
print("hello \(hello)")

声明时可以不指定类型,编译器会自动推断其类型。

也可以像下面这样指定:

let label: String = "The width is"

数据类型 #

Int #

Float #

String #

Bool #

String #

可选类型 #

恒等运算符 #

  • 相同(===

  • 不相同(!==

请注意,“相同”(用三个等号表示,===)与“等于”(用两个等号表示,==)的不同。“相同”表示两个类类型(class type)的常量或者变量引用同一个类实例。“等于”表示两个实例的值“相等”或“等价”,判定时要遵照设计者定义的评判标准。

单引号和双引号? #

类型转换 #

值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。

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

也可以在通过反斜杠\()在字符串中打印出来。

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

数据结构 #

Array #

Set #

Dictionary #

数组 #

使用初始化语法来创建一个空数组或者空字典。

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

字典 #

struct #

struct ReplaxModel: Hashable, Codable {
    var id: Int
    var name: String
    var park: String
    var state: String
    var description: String
    
    private var imageName: String
}

操作 #

下标 #

subscript

关键字 #

guard #

if 语句一样,guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码。

goto #

some #

程序控制 #

if #

if hello == "world" {
    print("yes")
}

if (hello == "world") {
    print("yes")
}

switch #

for #

case 1

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")
}

case 2

for _ in 0..<10 {
    let newItem = Item(context: viewContext)
    newItem.timestamp = Date()
}

continue

break

select #

do…catch 错误处理 #

枚举 #

  1. 一旦确定变量的类型,再次为其赋值可以省略枚举类型名,使用更简短的点语法即可。
  2. 与其他语言的枚举不一样的是,swift 的枚举成员在创建时不会被赋予一个默认的整型值。
  3. switch 时 case 要覆盖全,或者用 default ,不然会报错。
enum NumEnum {
    case one
    case two
    case three
    case four
}

print(NumEnum.one)

let n = NumEnum.one

switch n {
case .one:
    print("one")
case .two:
    print("two")
default:
    print("default")
}

关联值 #

原始值 #

递归枚举 #

函数 #

函数可以作为另一个函数的返回值。

结构体 #

可变行为(mutating)

#

下标 #

subscript

闭包 #

闭包的函数体部分由关键字 in 引入。该关键字表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始。

断言 #

assert 使用断言进行调试 #

只在 debug 下生效

precondition 强制先决条件 #

debug 和 release 都生效

装饰器 #

@State

@Binding

@EnvironmentObject

@Environment

https://juejin.cn/post/6844903924084768776

# 井号的使用 #

# 在函数(或者方法)的参数名前添加"#",可以使该参数拥有相同的本地参数名和外部参数名。函数(或方法)调用时强制使用外部参数名,否则编译错误。

_ 下划线的使用 #

_ 下划线可以用来省略外部参数名

特性(@) #

@objc #

@main #

$ 的使用 #

访问控制 #

  • open
  • public
  • internal
  • fileprivate
  • private

参考 #