swiftui - 如何在 Swift 中理解这种语法 (a ? b ? c : d : 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()
}
}
解决方案
Is 是一个嵌套的三元运算符。
对 swift 不太熟悉,所以我不知道我的代码片段是否与 Swift 完全一致,但我们将其称为 psudeocode 来说明您的示例的作用:
if a {
if b {
c
} else {
d
}
} else {
c
}
推荐阅读
- c++ - OpenGL 16 位模板缓冲区?
- python - 为什么删除字符串中非字母字符的正则表达式函数不起作用?
- javascript - 多字段搜索表单,无需为每个搜索条件复制组件
- python - 如何根据在 Django 的 ModelChoiceField 中选择的值命名模型实例?
- mysql - 如何使用 SELECT 和 IF 条件在 mysql 中触发?
- javascript - 如何在javascript中查找id和设置属性
- javascript - 在odoo中修改主仪表板
- javascript - 直接导航到内部 url 时反应 NextJS 502 BAD_GATEWAY
- python-3.x - 如何判断小数和日期(ex 12.4.5)
- gradle - Gradle 在构建时抛出 OutOfMemoryException