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

你可能感兴趣的:(swift源码之 _modify yield)