xcode swift

I'm new to this coding thing and I came across this error saying "Cannot assign value of type 'ScanResult' to type 'String'" in the line "self.scannedCode = code"

The attached is my code for reference import SwiftUI import CodeScanner

struct print: View {   @State var isPresentingScanner = false   @State var scannedCode: String = "Scan QR code on mask box"       var scannerSheet : some View {     CodeScannerView(       codeTypes: [.qr],       completion: { result in         if case let .success(code) = result {           self.scannedCode = code           self.isPresentingScanner = false                     }       }                 )   }       var body: some View {     VStack(spacing: 10) {       Text(scannedCode)               Button ("Scan QR Code") {         self.isPresentingScanner = true       }               .sheet(isPresented: $isPresentingScanner) {         self.scannerSheet       }     }   } }

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

You are new here, so welcome.

  • When you post code, use "Paste and MatchStyle" to paste code and use code formatter too (<>).
  • Use the appropriate tags: here it is more Swift or SwiftUI than the ones you selected.
  • Remember that struct names should start with uppercase. And reusing an existing func (print) is not a good idea. So, I changed in MyPrint.

You'll get this:

struct MyPrint: View {
    @State var isPresentingScanner = false
    @State var scannedCode: String = "Scan QR code on mask box"
    var scannerSheet : some View {
        CodeScannerView(
            codeTypes: [.qr],
            completion: { result in
                if case let .success(code) = result {
                    self.scannedCode = code
                    self.isPresentingScanner = false
                }

            } )
        
    }
    var body: some View {
        VStack(spacing: 10) {
            Text(scannedCode)
            Button ("Scan QR Code") {
                self.isPresentingScanner = true
                
            }
            .sheet(isPresented: $isPresentingScanner) {
                self.scannerSheet
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MyPrint()
        
    }
    
}
  • Where is CodeScannerView defined ?
  • How is ScanResult defined ?

Problem is that ScanResult is not a String. Without exact definition, I can only guess. You could try (not sure it'll work here):

self.scannedCode = code.description

Otherwise, you need to find in ScanResult how to get the description string.

xcode swift
 
 
Q