Tags
swift
Asked 4 years ago
13 Jan 2020
Views 3230
iptracker

iptracker posted

Cast from "Data" to unrelated type "String" always fails


  let encoder = JSONEncoder()
                                        encoder.outputFormatting = .prettyPrinted
                                        let data = try! encoder.encode(myLoactionlist) as! String
                                        
                                         UserDefaults.standard.set(data, forKey: "locationlist")
 
 

on run i get following crash
Cast from "Data" to unrelated type "String" always fails
fatso

fatso
answered Apr 25 '23 00:00

The error message "Cast from 'Data' to unrelated type 'String' always fails" is a runtime error that occurs when you try to convert a Data object to a String object, but the two types are not compatible.

To fix this error, you need to use the appropriate method or initializer to convert the Data object to a String object. One way to do this is to use the String(decoding:as:) initializer, which takes a Data object and an encoding and returns a String object:



let data = Data([72, 101, 108, 108, 111]) // "Hello" in ASCII code
let string = String(decoding: data, as: UTF8.self)
print(string) // prints "Hello"

In this example, we use the String(decoding:as :) initializer to decode the Data object data using the UTF8 encoding, which returns a String object.

Alternatively, you can use the String(data:encoding: ) initializer, which takes a Data object and an encoding and returns an optional String object:


let data = Data([72, 101, 108, 108, 111]) // "Hello" in ASCII code
if let string = String(data: data, encoding: .utf8) {
    print(string) // prints "Hello"
} else {
    print("Invalid data or encoding")
}

In this example, we use the String(data:encoding: ) initializer to create a String object from the Data object data using the UTF8 encoding. If the data and encoding are valid, the initializer returns a String object. Otherwise, it returns nil , which we can handle with an optional binding (if let statement).

By using the appropriate method or initializer, you can avoid the "Cast from 'Data' to unrelated type 'String' always fails" error and safely convert Data objects to String objects in your Swift code.
Post Answer