'How to convert Any? to Data in swift [duplicate]

I need to convert from type Any? to Data.

something like this

func getItem(item:Any?) {
    let data = convertToData(item)
}


Solution 1:[1]

You can do like this:

func getItem(item:Any?) {
    if let data = item as? Data {
      // do your thing
    }else {
      // not convertible to Data
    }
}

Solution 2:[2]

You can't convert Any? to data because Any? does not have a known type. It's literally any type at all (or nil, since you have an optional Any. you can use a conditional cast to try to cast your value to data, but it may fail:

func getItem(item:Any?) {
    guard let data = Data(item) else {
        return
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anuran Barman
Solution 2 Pylyp Dukhov