Why can't I pass an implicitly unwrapped optional as an UnsafeMutablePointer?

前端 未结 1 1628
南方客
南方客 2021-01-06 12:04

It seems that Xcode 9.3 does fix one issue I was having, but in Swift 4.1 the second half of this code still doesn\'t compile:

var obj: SomeClass!    ; class         


        
相关标签:
1条回答
  • 2021-01-06 12:32

    I'm afraid this is another lingering bug around implicitly unwrapped optionals (IUOs).

    It has already been fixed though (almost certainly as a result of the recent-ish work to completely remove IUOs from the type system) – it compiles in the latest dev snapshots, and therefore will make it into 4.2 (final re-branch from master is April 20).

    Until 4.2 rolls around, one possible workaround would be to use a forwarding computed variable in order to treat the IUO as a strong Optional type:

    class SomeClass {}
    
    var obj: SomeClass!
    var _optionalObj: SomeClass? {
      get { return obj }
      set { obj = newValue }
    }
    
    func pointerFunc(_: UnsafeMutablePointer<SomeClass?>) {}
    pointerFunc(&_optionalObj)
    

    (that is, assuming you're okay with having the pointer point to a temporary value – i.e you're not relying on the pointer value being stable or unique, such as you would be if this were to be used, for example, as an associated object key)

    0 讨论(0)
提交回复
热议问题