首页 > 解决方案 > 不能对“Bool”类型的非可选值使用可选链接

问题描述

为什么我不能使用c?swiftui 中的 1 : 2 语法?有什么解决办法吗?

import SwiftUI

struct ContentView: View {
  var c: Bool = false
    var body: some View {
        Text("Hello World")
          .foregroundColor(c? .red : .blue)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

标签: swift

解决方案


要正确使用三元运算,您需要在 thec和 the之间放置一个空格?

.foregroundColor(c ? .red : .blue)

你可以在这里看到更多,在三元条件运算符下的 Swift 文档中


推荐阅读