且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能将隐式展开的可选内容作为UnsafeMutablePointer传递?

更新时间:2022-12-15 12:45:58

恐怕这是围绕隐式展开的可选对象(IUO)的另一个挥之不去的错误.

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

尽管它已得到修复(几乎可以肯定是由于完全从类型系统中删除IUO )–它会编译到最新的dev快照中,因此将其变为4.2(从master最终分支到4月20日).

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).

在4.2发行之前,一种可能的解决方法是使用转发计算变量,以便将IUO视为强的Optional类型:

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)