闽公网安备 35020302035485号
// 在 '-default-isolation MainActor' 模式下
struct Image {
// 图片缓存在主线程保护下,很安全
staticvar cachedImage: [URL: Image] = [:]
staticfunc create(from url: URL) async throws -> Image {
iflet image = cachedImage[url] {
return image
}
let image = try await fetchImage(at: url)
cachedImage[url] = image
return image
}
// 用 @concurrent 标记需要并发执行的部分
@concurrent
staticfunc fetchImage(at url: URL) async throws -> Image {
let (data, _) = try await URLSession.shared.data(from: url)
return await decode(data: data)
}
}
这样可以避免数据竞争问题,并发代码更安全。struct Game {
// 40 个 Sprite,直接在结构体内部存储
var bricks: [40 of Sprite]
init(_ brickSprite: Sprite) {
bricks = .init(repeating: brickSprite)
}
}
适合需要大量小对象地场景,比如游戏开发。// 安全访问 C 风格数组
func processData(_ span: Span<UInt8>) {
for byte in span {
// 处理数据,编译器保证内存有效
}
}
比 UnsafePointer 更安全。.InlineArray 和 Span 类型
.DocC 文档实时预览
.target(
name: "MyLibrary",
swiftSettings: [
.treatAllWarnings(as: .error), // 所有警告当错误
.treatWarning("DeprecatedDeclaration", as: .warning), // 除了废弃API警告
]
)
Macro 编译优化Task("下载图片") {
let image = try await downloadImage()
// 调试时能看到这是"下载图片"任务
}
核心库更新import Subprocess
// 堆代码 duidaima.com
let swiftPath = FilePath("/usr/bin/swift")
let result = try await run(
.path(swiftPath),
arguments: ["--version"]
)
let swiftVersion = result.standardOutput
这个框架之后有时间再详细介绍。// 定义通知类型
struct UserLoginNotification: MainActorMessage {
let username: String
let timestamp: Date
}
// 发送通知
NotificationCenter.default.post(UserLoginNotification(
username: "john",
timestamp: Date()
))
// 接收通知 - 类型安全!
for await notification inNotificationCenter.default.notifications(for: UserLoginNotification.self) {
print("用户 \(notification.username) 登录了")
}
Swift Testing@Test func `square() returns x * x`() {
#expect(square(4) == 4 * 4)
}
WebAssembly 支持