首页 > 解决方案 > 如何在 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()
    }
}

标签: swiftuioptional

解决方案


Is 是一个嵌套的三元运算符

对 swift 不太熟悉,所以我不知道我的代码片段是否与 Swift 完全一致,但我们将其称为 psudeocode 来说明您的示例的作用:

if a {
    if b {
        c
    } else {
        d
    }
} else {
    c
}

推荐阅读