GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Problem getting a string from a func

Forums > SwiftUI

I am having an issue with an error that I don't understand. I have a class that extracts some data from a binary file, and I want to return a string back to my view so I can present it. The relevant bit of my view code is:

struct ContentView: View {

@State var myString = ""

var body: some View {
    VStack {

        let bfr: BinFileReader = BinFileReader()
        myString = bfr.getMyString()                       //THIS IS WHERE I GET THE ERROR
        ....

    }
    .padding()
}

}

and in my Binary File reader class I have:

func getMyString() -> String {

    print("Number of elements in binData is: \(binData.count)")
    let MyString_Data = binData[17...32]
    let string = String(decoding: MyString_Data, as: UTF8.self)
    print(string)
    return string
}

and the error I get is: 'buildExpression' is unavailable: this expression does not conform to 'View'

I'm confused by the error - what does it mean and how can I fix it?

   

You can not have myString = bfr.getMyString() in the body.

Is the Binary File reader class an @Observable, if so

@State var bfr = BinFileReader()

var body: some View {
    VStack {

        Text(bfr.getMyString())
        ....

    }
    .padding()
}

Not sure what you are doing with myString

You get that error because body is a @ViewBuilder so that it conform to View

1      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.