Search code examples
iosswiftstringstring-comparisonswift5

Argument type 'String?' does not conform to expected type 'StringProtocol'


enter image description here

This error occurs when using compare on a String in Swift 5, it accepts only StringProtocol, but I want to use it on String and can't find nowhere how to do it.

I've searched all over and can't understand what seems to be the issue.


Solution

  • Problem that Optional<String> (aka String?) is not conform to StringProtocol (and that makes sense). You should unwrap optional, there is several ways:

    1. Unwrapping by if let/guard (if let version = dbData?.version { //compare })
    2. Providing default value ( `(dbData?.version ?? "")), which is not recommended, because it can provide unnecessary collisions
    3. Force unwrap dbData!.version, which is highly not recommended, because it can involve crashing an app, if Optional was nil