修改Swift中的引用类型参数;外面的变化是立即可见的吗?
Modifying reference type parameters in Swift; are changes immediately visible outside?
我有一个 Swift 游乐场,源文件夹中包含几个 classes。这些 classes 有 tick()
函数,可以用 while true { }
尽快调用。我正在使用并行线程来执行此操作,以阻止 Xcode 锁定,代码如下:
DispatchQueue.global(qos: .background).async {
BackgroundThread.startMainLoop(scene: scene)
}
// other file
public struct BackgroundThread {
public static func startMainLoop (scene: SKScene) {
let songController = SongController()
let uiManager = UIManager(scene: scene)
// The UIManager is going to modify this scene.
// Will the changes be available to BackgroundThread and/or the main file?
while true {
songController.tick()
uiManager.tick()
}
}
}
因为主要的 playground 脚本非常慢,我已将重复循环移动到 Sources 文件夹中已编译的 class。
我正在将一个 SKScene
对象传递给一个 UIManager
编译的 class,我需要在这个(相对复杂的)场景中更快地更新 UI主要的 playground 脚本可以管理。
主要的 playground 脚本在并行线程中调用了一个 startMainLoop()
函数。它传入 SKScene
对象。这个函数永远不会 returns,因为它包含一个永无止境的循环。有没有一种方法可以修改传递的对象,以修改屏幕上显示的场景,实时,而无需函数 return (这意味着 inout
不是一个选项),假设默认情况下不会发生这种情况?
引用类型意味着该值是一个引用——即指向一个对象的指针。当你传递或赋值一个引用时,你得到了引用的一个副本(没有inout
是传值),但是引用的多个副本指向同一个对象,并且通过任何对对象的修改指向它的引用通过指向它的任何其他引用可见。
我有一个 Swift 游乐场,源文件夹中包含几个 classes。这些 classes 有 tick()
函数,可以用 while true { }
尽快调用。我正在使用并行线程来执行此操作,以阻止 Xcode 锁定,代码如下:
DispatchQueue.global(qos: .background).async {
BackgroundThread.startMainLoop(scene: scene)
}
// other file
public struct BackgroundThread {
public static func startMainLoop (scene: SKScene) {
let songController = SongController()
let uiManager = UIManager(scene: scene)
// The UIManager is going to modify this scene.
// Will the changes be available to BackgroundThread and/or the main file?
while true {
songController.tick()
uiManager.tick()
}
}
}
因为主要的 playground 脚本非常慢,我已将重复循环移动到 Sources 文件夹中已编译的 class。
我正在将一个 SKScene
对象传递给一个 UIManager
编译的 class,我需要在这个(相对复杂的)场景中更快地更新 UI主要的 playground 脚本可以管理。
主要的 playground 脚本在并行线程中调用了一个 startMainLoop()
函数。它传入 SKScene
对象。这个函数永远不会 returns,因为它包含一个永无止境的循环。有没有一种方法可以修改传递的对象,以修改屏幕上显示的场景,实时,而无需函数 return (这意味着 inout
不是一个选项),假设默认情况下不会发生这种情况?
引用类型意味着该值是一个引用——即指向一个对象的指针。当你传递或赋值一个引用时,你得到了引用的一个副本(没有inout
是传值),但是引用的多个副本指向同一个对象,并且通过任何对对象的修改指向它的引用通过指向它的任何其他引用可见。