Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure containing a declaration cannot be used with function builder 'ViewBuilder'

Tags:

swift

swiftui

I cant declare a variable inside swift ui view block

 var body: some View {
     let isHuman = false
     Text("Levels \(isHuman)")
 }
like image 268
yara Avatar asked Nov 10 '19 14:11

yara


Video Answer


2 Answers

you shouldn't create a variable inside the SwiftUI builder block, you should create it out of the body scope,

  var isPlaying = false

  var body: some View {
      Text("Levels \(isPlaying)")
  }

Swift UI uses a function builders block that can only contain content that is understandable by the builder. Then what you should write inside the builder block is only View Type and [View]  However, if you want to declare a variable you could work around it by introducing it to a new subclass

The purpose of this feature is to enable the creation of embedded DSLs in Swift -- allowing you to define content that gets translated to something else down the line

Also, you could use.

 @State var isPlaying: Bool = false

Note

review your code twice before doing the workaround, probably you have a misunderstanding about how swift-UI works?

like image 131
Abuzeid Avatar answered Oct 06 '22 08:10

Abuzeid


Not so bad, you can ... another question whether you really need it, but when you really need, you do know that you can. You just need to remember that view builder must return some View and it must be same type in all possible branches

var body: some View {
    let value = "" // construct somewhere or something
    return Text("Levels \(value)")
}
like image 24
Asperi Avatar answered Oct 06 '22 09:10

Asperi