新版 SwiftUI 的 ViewBuilder 可以輸入 if let,switch & 宣告變數常數

新版的 SwiftUI 現在可以在 ViewBuilder 裡輸入 if let,switch & 宣告變數常數了。

if let

struct ProfileView: View {

var userName: String
var imageName: String?

var body: some View {
VStack {
Text(userName)
if let imageName = imageName {
Image(imageName)
.resizable()
.scaledToFit()
}
}

}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ProfileView(userName: "peter", imageName: "peter")
}
}

switch

enum Gender {
case boy, girl
}
struct ProfileView: View {

var userName: String
var gender: Gender

var body: some View {
VStack {
Text(userName)
switch gender {
case .boy:
Text("👦")
case .girl:
Text("👧")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ProfileView(userName: "peter", gender: .boy)
}
}

宣告變數常數

struct ContentView: View {

var body: some View {
HStack {
let number1 = Int.random(in: 1...6)
let number2 = Int.random(in: 1...6)
let number3 = Int.random(in: 1...6)
Image(systemName: "\(number1).circle")
.resizable()
Image(systemName: "\(number2).circle")
.resizable()
Image(systemName: "\(number3).circle")
.resizable()
}
.scaledToFit()
}
}

相反的,在舊版的 SwiftUI,在 ViewBuilder 宣告變數常數將產生錯誤,顯示 Closure containing a declaration cannot be used with function builder ‘ViewBuilder’。

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
彼得潘的 iOS App Neverland

彼得潘的 iOS App Neverland

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com