Search code examples
swifttextoption-typeunwrap

Optional in text view showing when printing


Hi all I have tried a few solutions but no luck.

I am getting the text from Data Core, but the textview has optional on it.

when it prints it shows optional in the text.

page22TextView?.text = ("\(trans.value(forKey: "page22"))")

can anyone shed light on this ! have tried to unwrap but it stillelow: shows.

the full function is below:

func getTranscriptions () {
    //create a fetch request, telling it about the entity

    let fetchRequest: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()


    do {
        //go get the results
        let searchResults = try getContext().fetch(fetchRequest)

        //I like to check the size of the returned results!
        print ("num of results = \(searchResults.count)")

        //You need to convert to NSManagedObject to use 'for' loops
        for trans in searchResults as [NSManagedObject] {


            page22TextView?.text = ("\(trans.value(forKey: "page22"))")
            //get the Key Value pairs (although there may be a better way to do that...
            print("\(trans.value(forKey: "page22"))")

        }
    } catch {
        print("Error with request: \(error)")
    }
}

Solution

  • try with if-let statement:

    if let result = trans.value(forKey: "page22") {
    
        page22TextView?.text = result
    }
    

    Or try with guard statement:

    guard let result = trans.value(forKey: "page22") else { return }
    page22TextView?.text = String(describing: result)
    

    Or you can force upwrap it like:

    let result = trans.value(forKey: "page22")
    
    if result != nil {
    
        page22TextView?.text = result! as! String
    }
    

    Or you can follow the way suggested by @MrugeshTank below in answers