跳转到内容
代码片段·免费

Swift 代码片段

20 个 Swift 代码片段:可选值、枚举和 Result、带扩展的协议、async/await 与 URLSession、Codable、SwiftUI 视图和状态、@Observable 模型以及 XCTest。部分需要 Swift 5.9 或 iOS 17。

免费安装。

如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。

预览

20 个中的 5 个

Unwrap with if letiflet

Run a block only when the optional has a value

if let ${1:user} = ${2:currentUser} {
    $0
}

Switch over an enumswitchenum

Switch with one case per enum value

switch ${1:direction} {
case .${2:north}:
    $0
case .${3:south}:
    break
}

Protocol with a default implementationprotoc

Protocol plus an extension that every conforming type gets for free

protocol ${1:Describable} {
    var ${2:summary}: String { get }
}

extension ${1:Describable} {
    func describe() {
        print(${2:summary})
    }
}

Async throwing functionasyncf

Function called with try await

func ${1:fetchUser}(id: ${2:Int}) async throws -> ${3:User} {
    $0
}

Task with error handlingtaskb

Start async work from synchronous code and catch its errors

Task {
    do {
        ${1:try await load()}
    } catch {
        print(error)
    }
}

1.0.0 的变更

首个版本。

相关