微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐