Error on Swift3 Cannot convert value of type 'UnsafePointer<xmlChar>'

Asked 2 years ago, Updated 2 years ago, 70 views

After converting from Swift2 to Swift3, the following error occurred and cannot be resolved.

Cannot convert value of type 'UnsafePointer<xmlChar>' (aka'UnsafePointer<UInt8>') to expected argument type 'UnsafePointer<_>'

The affected code is as follows: String (cString: UnsafePointer<CChar>(char!)) causes an error.

static func fromXmlChar(_char:UnsafePointer<xmlChar>?)->String?{
    if char!=nil{
        return String (cString: UnsafePointer<CChar>(char!))
    } else{
        return nil
    }
}

swift swift3 swift2

2022-09-30 16:05

1 Answers

I threw away the version of Xcode with the Swift3 compiler a long time ago, so I only tested it in Swift 3.3 mode of Xcode 9.4.1, but Swift3 should have defined two types of String.init(cString:) so I don't need a pointer translation ( UnsafePointer < CC)...

init(cString:UnsafePointer<CChar>)<- Who is using your current code

init(cString:UnsafePointer<UInt8>)<- You can use it without conversion

static func fromXmlChar(_char:UnsafePointer<xmlChar>?)->String?{
        if char!=nil{
            return String (cString:char!) // < - pass `UnsafePointer<xmlChar>` directly without conversion
        } else{
            return nil
        }
    }

Alternatively, using conditional bindings is more Swift-like.

static func fromXmlChar(_char:UnsafePointer<xmlChar>?)->String?{
        iflet cStr = char {
            return String (cString:cStr)
        } else{
            return nil
        }
    }

I don't know if the conversion to Swift4, Swift5 will take place soon, but writing everywhere as Swift-like as possible tends to increase the probability of successful conversion.

In addition, code that cannot be compiled by the Swift3 compiler may be compiled by the Swift3.3 mode of the Swift4 compiler.If the above code cannot be compiled with your Xcode, please let me know.


2022-09-30 16:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.