没有 C 风格的指针 (Unsafe Pointer),正如问题所问的那样,但是对象是通过引用共享的,结构是按值共享的:
Swift assign、pass 和 return 引用 reference type 的值和值类型的副本
structures 在代码中传递时总是被复制,但 classes 是通过引用传递的。
例如
如何拥有指向对象的指针/引用
class Song {
init(title: String, image: String, file: String, volume: Float, queuePlayer: AVQueuePlayer, playerLooper: AVPlayerLooper?) {
self.title = title
self.image = image
...
}
var title: String
var image: String
...
}
var aSong = Song(title: "", image: "", ...)
var arrOfSongReferences: [Song] = [Song]()
arrOfSongReferences.append(aSong)
var ptrToASong: Song = aSong
aSong = nil
// Due to Swift garbage collection ARC (Automatic Reference Counting), we still have references to the original aSong object so it won't be deleted
如果数据是结构,你不能这样做
struct Song {
var title: String
var image: String
...
}
var aSong: Song = Song(title: "", image: "", ...)
var copyOfASong: Song = aSong
方法
你也可以通过引用传递给函数
// this would be inside a class, perhaps Player. It doesn't have to be a static btw
static func playSound(_ sound: inout Song, volume: Float = 0.0) {
if (sound.playerLooper == nil) {
...
}
}
// usage
Player.playSound(sound: &aSong)