15.2 Swift字符串的拷贝

前端之家收集整理的这篇文章主要介绍了15.2 Swift字符串的拷贝前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

/**

2)字符串拷贝

@H_404_16@ */

var swiftStr: String = "Hello"

var swiftStr1: String = swiftStr

/**

@H_404_16@ public struct String {

@H_404_16@ /// Creates an empty string.

@H_404_16@ public init()


@H_404_16@ 我们点击安住Command 点击String可以看到是 结构体类型,值类型

值类型的赋值操作是深拷贝,

所有这个字符串的这种操作都是深拷贝。

@H_404_16@ */

/**

我们可以验证一下上面的赋值操作是否是深拷贝

@H_404_16@ */

@H_404_16@ // 改变 swiftStr1

swiftStr1 += " World"

print("swiftStr==\(swiftStr)")

print("swiftStr1==\(swiftStr1)")

/**

@H_404_16@ swiftStr==Hello

@H_404_16@ swiftStr1==Hello World

@H_404_16@ */

/**

@H_404_16@ 我们可以看到改变swiftStr1后,swiftStr并没有被改变啊。

@H_404_16@ 所以上面是深拷贝。

@H_404_16@ */

print("swiftStr.Address==\(Unmanaged<AnyObject>.passUnretained(swiftStr as AnyObject).toOpaque())")

print("swiftStr1.Address==\(Unmanaged<AnyObject>.passUnretained(swiftStr1 as AnyObject).toOpaque())")


/**

打印出来的地址也不一样啊,所以是深拷贝。

@H_404_16@ swiftStr.Address==0x0000608000051e20

@H_404_16@ swiftStr1.Address==0x0000608000051f40

@H_404_16@ */

var ocStr: NSMutableString = NSMutableString.init(string: "balabala")

/**

@H_404_16@ 按住Command 点击NSMutableString,进入

@H_404_16@ open class NSMutableString : NSString {

@H_404_16@ /* NSMutableString primitive (funnel) method. See below for the other mutation methods.

@H_404_16@ */

@H_404_16@ open func replaceCharacters(in range: NSRange,with aString: String)

@H_404_16@ }


可以看到的是 class类型,是引用类型,所以是浅拷贝。

@H_404_16@ */

var ocStr1 = ocStr

@H_404_16@ // 改变ocStr1

ocStr1.insert("World",at: ocStr.length)

print("ocStr==\(ocStr)")

print("ocStr1==\(ocStr1)")

/**

@H_404_16@ ocStr==balabalaWorld

@H_404_16@ ocStr1==balabalaWorld

@H_404_16@ 改变ocStr1后,ocStr也改变了,是浅拷贝。

@H_404_16@ 这些都是系统来替我们做的,程序员不需要做。

@H_404_16@ */

猜你在找的Swift相关文章