我还是Swift的新手,可以从Apple阅读语言指南。
关于子字符串的“字符串”一章,我有一个关于子字符串内容变化的问题。当我更改子字符串而不将其转换为String时,原始字符串也应更改,而不必更改。
从子字符串的来源说明中可以看到,子字符串持有对部分字符串存储的引用。如果未将子字符串显式转换为字符串,则对子字符串的操作应在字符串内容上生效。
下面的代码描述了问题
var originalString = "hello, world!"
var varSubString = originalString[..<originalString.index(originalString.startIndex, offsetBy: 4)]
print(varSubString)
//print "hell"
varSubString.insert("a", at: varSubString.endIndex)
print(varSubString)
//print "hella"
print(originalString)
//print "hello, world!", but expected to print "hella, world"
答案 0 :(得分:1)
Please see the Apple document on Substring and String optimization.
Like strings, each substring has a region of memory where the characters that make up the substring are stored. The difference between strings and substrings is that, as a performance optimization, a substring can reuse part of the memory that’s used to store the original string, or part of the memory that’s used to store another substring. (Strings have a similar optimization, but if two strings share memory, they are equal.) This performance optimization means you don’t have to pay the performance cost of copying memory until you modify either the string or substring.
All these optimizations are applicable until either string or substring is modified. If it is modified, string ans substring will be a separate objects.
答案 1 :(得分:1)
这意味着,如果您更改子字符串或原始字符串,它们将不再是参考。
https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
此性能优化意味着您无需支付 复制内存直到您修改任一字符串的性能成本 或子字符串
请注意长时间使用子字符串
因此,存储子字符串可能会延长字符串数据的寿命 无法通过其他方式访问,可能看起来像是内存 泄漏。
import UIKit
var str = "Hello, playground"
let index = str.index(str.startIndex, offsetBy: 5)
var mySubstring = str[..<index] // Hello
print(str) // Hello
print(mySubstring) // Hello, playground
str = "Hallo, playground"
print(str) //Hallo, playground
print(mySubstring) //Hello