swift源码之 _modify yield


@inlinable
  public subscript(index: Int) -> Element {
    get {
      // This call may be hoisted or eliminated by the optimizer.  If
      // there is an inout violation, this value may be stale so needs to be
      // checked again below.
      let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()

      // Make sure the index is in range and wasNativeTypeChecked is
      // still valid.
      let token = _checkSubscript(
        index, wasNativeTypeChecked: wasNativeTypeChecked)

      return _getElement(
        index, wasNativeTypeChecked: wasNativeTypeChecked,
        matchingSubscriptCheck: token)
    }
    _modify {
      _makeMutableAndUnique() // makes the array native, too
      _checkSubscript_native(index)
      let address = _buffer.subscriptBaseAddress + index
      yield &address.pointee
    }
  }

最近在swift源码中发现_modify { yield }
起初我以为是生成器
直到后面看到runtime/KeyPaths.cpp时才发现是下标访问相关的
写个测试类

class Test {
    var vale = 0
    public subscript(index: Int) -> Int {
      get {
        return 0
      }
      _modify {
        yield &vale
      }
    }
}

let ctst = Test()
print(ctst.vale)
ctst[0] = 20
print(ctst.vale)
ctst[9] = 90
print(ctst.vale)

打印


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。