Swift里字符串(五)Native strings
Native strings have tail-allocated storage, which begins at an offset of nativeBias from the storage object's address. String literals, which reside in the constant section, are encoded as their start address minus nativeBias, unifying code paths for both literals ("immortal native") and native strings. Native Strings are always managed by the Swift runtime.
即字符串数据从内部_object
的起始位置加上一个偏移处起始。
对应的类是__StringStorage
。
内存布局如下

在 OC runtime下,是 NSString 的子类。

子类化NSString
根据文档,提供了几个方法
@objc(length)
final internal var length: Int {
@_effects(readonly) @inline(__always) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
下起雨,也要勇敢前行