首页 > 解决方案 > Xcode 产生“分段错误:11”编译

问题描述

编译以下代码时,Xcode 版本 11.3.1 (11C504) 会抛出:
“错误:分段错误:11(在项目 'TestDel3' 的目标 'TestDel3' 中)”

如果我注释掉Image(systemName: systemName)并用它替换Image(systemName: "person")它编译

struct ContentView: View{
  var body: some View {
    UseButtonContainer( b: ButtonContainer("x1",systemName:"person") {print("c1")})
  }
}

struct UseButtonContainer: View{
  let b : ButtonContainer
  var body: some View {
    Button(action: {
      self.b.action();
      self.extraAction()
    }) { b.label}
  }

  func extraAction()->Void{
    print("extra action")
  }
}

struct ButtonContainer{
  let label: VStack<TupleView<(Image, Text)>>
  let action: ()-> Void

  init(_ text: String, systemName: String, action: @escaping ()-> Void){
    self.label = VStack{
      Image(systemName: systemName)     // Commenting out this line
      //Image(systemName: "person")     // and using this instead, it compiles
      Text(text)
    }
    self.action = action
  }
}

What's wrong here?

标签: swiftxcodeswiftui

解决方案


更新:以下变体有效

struct ButtonContainer{
  let label: VStack<TupleView<(Image, Text)>>
  let action: ()-> Void

  init(_ text: String, systemName: String, action: @escaping ()-> Void){
    self.label = VStack {
      Image(systemName: "\(systemName)") // << make it string literal !!!
      Text(text)
    }
    self.action = action
  }
}

初始(以防万一):

考虑到 SwiftUI 几乎在所有地方都使用不透明类型some View,使用擦除类型进行label编译和运行良好的方法(使用 Xcode 11.3.1 / iOS 13.3 测试)。我不确定您是否需要在这里使用显式类型,但请注意。

struct ButtonContainer{
  let label: AnyView
  let action: ()-> Void

  init(_ text: String, systemName: String, action: @escaping ()-> Void){
    self.label = AnyView(VStack {
      Image(systemName: systemName)
      Text(text)
    })
    self.action = action
  }
}

推荐阅读