Why does Swift return an unexpected pointer when converting an optional String into an UnsafePointer?

后端 未结 3 913
无人共我
无人共我 2021-01-06 02:12

I noticed some unusual behaviour when working with a C library which took strings in as const char * (which is converted to Swift as UnsafePointer

3条回答
  •  日久生厌
    2021-01-06 02:44

    Just to be clear, there is a workaround until Apple fixes this. Unwrap your optional Strings before passing them and everything will work fine.

    var anOptional: String?
    var anotherOptional: String?
    
    func mySwiftFunc() {
    
        let unwrappedA = anOptional!
        let unwrappedB = anotherOptional!
    
        myCStringFunc(unwrappedA, unwrappedB)
    
    }
    

提交回复
热议问题