小编Mar*_*Doe的帖子

如何在 Swift 中捕获异步闭包内的局部变量?

我在 Swift 5.5 和 iOS 15 中有以下代码

func getReviewIds() {
    
    var reviewIds: [Int] = []
    
    Task {
        let ids = await getReviewIdsFromGoogle()
        reviewIds.append(contentsOf: ids)
    }
    
    print("outside")
}

func getReviewIdsFromGoogle() async -> [Int] {
    await withUnsafeContinuation { continuation in
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            continuation.resume(returning: [1,2,3])
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

getReviewIdsFromGoogle我在以下行中收到函数错误:

reviewIds.append(contentsOf: ids)
Run Code Online (Sandbox Code Playgroud)

并发执行代码中捕获的 var 'reviewIds' 的突变

我知道我可以创建getReviewIdsFromGoogle一个async函数而不是使用async闭包,但是如何使用闭包解决这个问题。

async-await swift

31
推荐指数
2
解决办法
2万
查看次数

根据本地通知刷新 SwiftUI 视图

我有以下代码:

  @State private var isDataImported: Bool = false
    
    init() {
        NotificationCenter.default.addObserver(forName: .onDataImported, object: nil, queue: nil) { [self] notification in
            print("Data has been imported...")
            
            DispatchQueue.main.async {
                self.isDataImported = true
                print(self.isDataImported) // prints out false 
            }
            
           
        }
    }
Run Code Online (Sandbox Code Playgroud)

我可以调试并看到通知正在被触发。正在打印“数据已导入”行。我想更新 self.isDataImported 属性,然后刷新我的视图。

 if isDataImported {
              ShowDataView() 
            } else {
                ProgressView()
            }
Run Code Online (Sandbox Code Playgroud)

但视图 ShowDataView 永远不会显示,因为 isDataImported 始终为 false。我缺少什么?

ios swiftui

4
推荐指数
2
解决办法
5038
查看次数

在 RealityKit 中将不同的图像纹理材质应用于盒子的每一侧

我正在 RealityKit 中创建一个盒子,并希望对盒子的每一侧应用不同的纹理。我使用以下代码,但它总是在每一侧应用名为“lola”的第一个纹理作为材质。我错过了什么吗?

cancellable = TextureResource.loadAsync(named: "lola")
            .append(TextureResource.loadAsync(named: "cover"))
            .append(TextureResource.loadAsync(named: "purple_flower"))
            .append(TextureResource.loadAsync(named: "cover"))
            .append(TextureResource.loadAsync(named: "purple_flower"))
            .append(TextureResource.loadAsync(named: "cover"))
            
            .collect()
            .sink { [weak self] completion in
            if case let .failure(error) = completion {
                fatalError("Unable to load texture \(error)")
            }
            
            self?.cancellable?.cancel()
            
        } receiveValue: { textures in
            
            var materials: [UnlitMaterial] = []
            
            textures.forEach { texture in
                print(texture)
                var material = UnlitMaterial()
                material.color = .init(tint: .white, texture: .init(texture))
                materials.append(material)
            }
            
            box.model?.materials = materials
            anchor.addChild(box)
            arView.scene.addAnchor(anchor)
        }
Run Code Online (Sandbox Code Playgroud)

swift realitykit

4
推荐指数
1
解决办法
843
查看次数

RealityKit – 获取 ModelEntity 大小为 SIMD3<Float>

有没有办法知道 SIMD3 的 ModelEntity 的大小?一旦我获得了大小,我想将其传递给 CollisionComponent。

 let box = ModelEntity(mesh: MeshResource.generateBox(size: 0.2), 
                  materials: [SimpleMaterial(color: .green, isMetallic: true)])
 box.position.y = 0.3 
 box.generateCollisionShapes(recursive: true)
 box.physicsBody = PhysicsBodyComponent(massProperties: .default, 
                                              material: .default, 
                                                  mode: .dynamic)
            
 // I know I can use the following
 box.collision = CollisionComponent(shapes: [.generateBox(size: [0.2,0.2,0.2])], 
                                                          mode: .trigger, 
                                                        filter: .sensor)
            
 // but why not just pass the size of the box I created earlier. 
 box.collision = CollisionComponent(shapes: [PASS BOX SIZE HERE], 
                                      mode: .trigger, 
                                    filter: .sensor)
Run Code Online (Sandbox Code Playgroud)

swift realitykit

3
推荐指数
1
解决办法
1402
查看次数

UIViewControllerRepresentable 在 Xcode 14 iOS 16 上崩溃

我正在尝试在 Xcode 14 beta 和 iOS 16 中为我的视图控制器创建 Xcode 预览。当我运行代码时,它只会在对话框中抛出一些 Xcode 预览错误并使预览崩溃。我没有使用 Storyboard,所以我只是以编程方式加载 ViewController2。

import Foundation
import UIKit
import SwiftUI

final class ViewController2: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.green
    }
}

struct ViewController2_Previews: PreviewProvider {
    static var previews: some View {
        ViewController2()
    }
}

extension ViewController2: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> ViewController2 {
        ViewController2()
    }
    
    func updateUIViewController(_ uiViewController: ViewController2, context: Context) {
        
    }
}
Run Code Online (Sandbox Code Playgroud)

ios swiftui

3
推荐指数
1
解决办法
1736
查看次数

Swift Components.Url 返回错误的 URL

我实现了以下代码,我可以在其中传递资源名称,它应该为我提供 URL。我正在使用 Xcode 14 Beta 3。

 static let baseUrl = "localhost:8080"
 static func resource(for resourceName: String) -> URL? {
            
            var components = URLComponents()
            components.scheme = "http"
            components.percentEncodedHost = baseUrl
            components.path = "/\(resourceName)"
            return components.url
            
        }
Run Code Online (Sandbox Code Playgroud)

我将资源名称传递为“my-pets”,它应该返回,http://localhost:8080/my-pets但它不断返回http://my-pets。我不确定我在哪里犯了错误。

xcode swift nsurlcomponents xcode14

3
推荐指数
1
解决办法
995
查看次数