SwiftUI > IfLet 是一个实用工具库,它为 SwiftUI 添加了重新使用 if let
功能的方法。此外,它还增加了一个新的功能,相当于在 Binding
对象上使用 if let
。
由于此功能的性质,它具有与 SwiftUI 相同的要求
(目前)它只能作为 SwiftPM 包使用。
Swift Package Manager 是一个用于自动化 Swift 代码分发的工具,并且集成到 swift
编译器中。
您可以按照这里的说明,了解如何从 Xcode 将 Swift Package 添加到您的项目中。
设置好 Swift 包后,将其添加到 Package.swift
的 dependencies
值中。
dependencies: [
.package(url: "https://github.com/baguio/SwiftUI-IfLet.git", from: "0.3.0")
]
IfLet 和 IfBindingLet 每次只能构建一个 View,但这个 View 可以是一个 View group(Groups、Stacks 等)。
let foo : String? = nil
VStack {
IfLet(foo) { bar in
VStack {
Text("This won't appear because the variable used is nil")
Text(bar)
}
}
IfLet(foo, { bar in
Text(bar)
}, else: {
Text("This text will appear, since the variable used is nil")
})
}
@State var foo : String? = nil
VStack {
IfBindingLet($foo) { bar in
VStack {
Text("This won't appear because the variable used is nil")
TextField("Input", text: bar)
}
}
IfBindingLet($foo, { bar in
TextField("Input", text: bar)
}, else: {
Text("This text will appear, since the variable used is nil")
})
}
SwiftUI-IfLet 是在 MIT 许可下发布的。有关详细信息,请参见 LICENSE。