如何在 Swift 中理解此语法 (a ? b ? c : d : c)
How to comprehend this syntax (a ? b ? c : d : c) in Swift
我在 SwiftUI 教程中得到以下代码,如何理解这一行?我知道目的是将座椅颜色设置为强调色(蓝色)(如果选择),否则将其保留为默认灰色。
但是如何理解这种语法以及它在 Swift 中被称为什么术语?
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
struct ChairView: View {
var width: CGFloat = 50
var accentColor: Color = .blue
var seat = Seat.default
@State var isSelected = false
var isSelectable = true
var onSelect: ((Seat)->()) = {_ in }
var onDeselect: ((Seat)->()) = {_ in }
var body: some View {
VStack(spacing: 2) {
Rectangle()
.frame(width: self.width, height: self.width * 2/3)
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
.cornerRadius(width / 5)
Rectangle()
.frame(width: width - 10, height: width / 5)
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
.cornerRadius(width / 5)
}
}
}
struct ChairView_Previews: PreviewProvider {
static var previews: some View {
ChairView()
}
}
是嵌套的ternary operator.
不太熟悉 swift,所以我不知道我的代码片段是否会完全符合 Swift,但我们将其称为伪代码来表示您的示例所做的事情:
if a {
if b {
c
} else {
d
}
} else {
c
}
我在 SwiftUI 教程中得到以下代码,如何理解这一行?我知道目的是将座椅颜色设置为强调色(蓝色)(如果选择),否则将其保留为默认灰色。
但是如何理解这种语法以及它在 Swift 中被称为什么术语?
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
struct ChairView: View {
var width: CGFloat = 50
var accentColor: Color = .blue
var seat = Seat.default
@State var isSelected = false
var isSelectable = true
var onSelect: ((Seat)->()) = {_ in }
var onDeselect: ((Seat)->()) = {_ in }
var body: some View {
VStack(spacing: 2) {
Rectangle()
.frame(width: self.width, height: self.width * 2/3)
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
.cornerRadius(width / 5)
Rectangle()
.frame(width: width - 10, height: width / 5)
.foregroundColor(isSelectable ? isSelected ? accentColor : Color.gray.opacity(0.5) : accentColor)
.cornerRadius(width / 5)
}
}
}
struct ChairView_Previews: PreviewProvider {
static var previews: some View {
ChairView()
}
}
是嵌套的ternary operator.
不太熟悉 swift,所以我不知道我的代码片段是否会完全符合 Swift,但我们将其称为伪代码来表示您的示例所做的事情:
if a {
if b {
c
} else {
d
}
} else {
c
}