Swift 里字符串(九)UTF16View

即以 UTF16 编码的格式来查看字符串。

UTF16View 是一个结构体

  @_fixed_layout
  public struct UTF16View {
    @usableFromInline
    internal var _guts: _StringGuts

    @inlinable
    internal init(_ guts: _StringGuts) {
      self._guts = guts
      _invariantCheck()
    }
  }

UTF16View 遵守 BidirectionalCollection 协议

可以正向/反向遍历,核心代码如下:

  @inlinable @inline(__always)
  public func index(after i: Index) -> Index {
    if _slowPath(_guts.isForeign) { return _foreignIndex(after: i) }
    if _guts.isASCII { return i.nextEncoded }

    // For a BMP scalar (1-3 UTF-8 code units), advance past it. For a non-BMP
    // scalar, use a transcoded offset first.
    let len = _guts.fastUTF8ScalarLength(startingAt: i.encodedOffset)
    if len == 4 && i.transcodedOffset == 0 {
      return i.nextTranscoded
    }
    return i.strippingTranscoding.encoded(offsetBy: len)
  }

读写Stringutf16属性

  public var utf16: UTF16View {
    @inline(__always) get { return UTF16View(_guts) }
    @inline(__always) set { self = String(newValue._guts) }
  }

每次读,都会生成一个新的UTF16View
每次写,都会更新String内部的_guts

UTF8View 属性

UTF16View类似,也是一个结构体,也遵守BidirectionalCollection协议。

  public var utf8: UTF8View {
    @inline(__always) get { return UTF8View(self._guts) }
    set { self = String(newValue._guts) }
  }

posted on 2019-03-20 08:29  花老🐯  阅读(183)  评论(0编辑  收藏  举报

导航