AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[swift](coding)

Martin Hope
bkbeachlabs
Asked: 2025-04-30 23:59:07 +0800 CST

从 .async 调用 .sync 时外部调度上下文会发生什么?

  • 7

我偶然发现了一位前开发人员编写的这段代码,但不明白其中的注释。

这似乎意味着使用外部DispatchQueue.main.async调用将满足Apple使用主队列修改UIImageView的要求。

我的问题:我理解主队列被阻塞是因为它正在等待来自内部队列的同步响应。但是这种方法是否会使在主队列上强制调用 ImageView API 失效?它显然不再是主队列了。

    private let imageViewQueue = DispatchQueue(label: "com.company.imageViewQueue")
    private var imageView: UIImageView?
    
    ...
    
    func updateImageView(viewer: UIImageView) {
        // have to do this on the main queue as well AND make sure we guard our viewer
        DispatchQueue.main.async {
            self.imageViewQueue.sync {
                self.imageView = viewer
            }
        }
    }

感谢您提供的任何帮助,帮助我们了解这里发生的事情。

swift
  • 1 个回答
  • 22 Views
Martin Hope
Whirlwind
Asked: 2025-04-30 16:47:55 +0800 CST

createBackingData() 方法起什么作用?

  • 6

我注意到当我创建一个@Model并转到Xcode的Refactor->Generate成员初始化器时,Xcode会执行以下操作:

@Model
    class A {
        internal init(a: String = "", b: Date = Date(), _$backingData: any BackingData<SchemaV2.A> = A.createBackingData()) {
            self.a = a
            self.b = b
            self._$backingData = _$backingData
        }
        
        var a: String = ""
        var b: Date = Date()
    }

如果我使用自己的初始化程序手动执行此操作,我绝不会使用类似的东西createBackingData()。它的用途是什么?

swift
  • 1 个回答
  • 31 Views
Martin Hope
Whirlwind
Asked: 2025-04-30 16:20:06 +0800 CST

当上下文保存设置为自动时,“modelContext.save()”有意义吗?

  • 6

由于它提供的便利之一SwiftData是在模型上下文中添加或更改某些内容时自动保存记录,那么显式调用save()会有什么区别吗?我想在两种情况下,SwiftData都会决定吗?

@ModelActor
public actor DataHandler {
    @discardableResult
    public func new(item: Item) throws -> PersistentIdentifier {
      modelContext.insert(item)
      try modelContext.save()
      return item.persistentModelID
    }
    
  @discardableResult
  public func newEmptyItem() throws -> PersistentIdentifier {
    let item = Item()
    modelContext.insert(item)
    try modelContext.save()
    return item.persistentModelID
  }

我可以删除这一行吗:

try modelContext.save()

不用担心?

swift
  • 2 个回答
  • 35 Views
Martin Hope
HL666
Asked: 2025-04-30 06:55:21 +0800 CST

Swift 元类型检查中的奇怪行为

  • 6

我正在思考这个问题的答案:如何测试泛型变量是否属于 AnyObject 类型

该解决方案似乎不再起作用。我有以下代码:

public struct ObjectHashable<T>: Hashable {
  
  public let object: T
  
  public init(object: T) {
    
    let t1 = type(of: object)
    let b1 = t1 is AnyClass
    print(t1) // Plugin
    print(b1) // false
    
    let t2 = T.self
    let b2 = t2 is AnyClass
    print(t2) // Plugin 
    print(b2) // false
    
    let t3 = Mirror(reflecting: object).subjectType 
    let b3 = t3 is AnyClass 
    print(t3) // P
    print(b3) // true 

    self.object = object
    
  }
  
  public static func ==(lhs: Self, rhs: Self) -> Bool {
    return true
  }
  
  public func hash(into hasher: inout Hasher) {
  }
}

protocol Plugin: AnyObject {}
class P: Plugin {}

typealias PluginHashable = ObjectHashable<Plugin>

PluginHashable(object: P())

这是一个令人惊讶的行为。

1.

let t1 = type(of: object)

type(of:)应该返回动态类型,即P,而不是Plugin。但我打印出了“插件”。

2.

let b1 = t1 is AnyClass

因为 t1 是引用类型,所以它不应该是真的吗?(基于此处的答案:如何测试泛型变量是否属于 AnyObject 类型)

3.

let t2 = T.self

打印出来Plugin,这是有道理的,因为我输入Plugin了<>

4.

let b2 = t2 is AnyClass

这是错误的,但我认为出于同样的原因,它应该是正确的

5.

    let t3 = Mirror(reflecting: object).subjectType // P

打印出来P,这是有道理的

6.

    let b3 = t3 is AnyClass // true

确实如此,这很有道理。但为什么它与其他两种情况不同呢?

swift
  • 1 个回答
  • 47 Views
Martin Hope
HL666
Asked: 2025-04-29 12:18:10 +0800 CST

如何使协议包装器(而非协议本身)符合 Swift 中的 Hashable

  • 5

我有一个仅限于类类型的协议:

protocol Plugin: AnyObject {}

现在我想使用插件作为哈希表的键。我不想让Plugin协议继承自Hashable,因为这样我就得any Plugin在所有地方都写一遍(因为它会从其父协议继承“自身要求”)。

为了解决这个问题,我想创建一个通用包装器。我不想使用AnyHashable,因为我希望在出现错误时使用更严格的类型。

public struct ObjectHashable<T: AnyObject>: Hashable {
  
  public let object: T
  
  public init(object: T) {
    self.object = object
  }
  
  public static func ==(lhs: Self, rhs: Self) -> Bool {
    return ObjectIdentifier(lhs.object) == ObjectIdentifier(rhs.object)
  }
  
  public func hash(into hasher: inout Hasher) {
    hasher.combine(ObjectIdentifier(object))
  }
}

现在我想做类似的事情

typealias PluginHashable = ObjectHashable<Plugin>

然而,这给了我错误:

要求指定为“T”:“AnyObject”[其中T = 任何插件]

所以我把它改成了

typealias PluginHashable = ObjectHashable<any Plugin>

我遇到了同样的错误:

要求指定为“T”:“AnyObject”[其中T = 任何插件]

我的理解是,虽然Plugin协议被限制为类类型,但any Plugin事实并非如此。但是,我不知道下一步该怎么做。

更新:

如果我不使用通用的 for ObjectHashable,它就会起作用:

public struct PluginHashable: Hashable {
  
  public let plugin: Plugin
  
  public init(plugin: Plugin) {
    self.plugin = plugin
  }
  
  public static func ==(lhs: Self, rhs: Self) -> Bool {
    return ObjectIdentifier(lhs.plugin) == ObjectIdentifier(rhs.plugin)
  }
  
  public func hash(into hasher: inout Hasher) {
    hasher.combine(ObjectIdentifier(plugin))
  }
}

但是,这个解决方案仅适用于Plugin协议,因此并不理想。我更希望有一个适用于所有类似情况的解决方案。

swift
  • 1 个回答
  • 49 Views
Martin Hope
cluster1
Asked: 2025-04-28 17:41:47 +0800 CST

Swift @MainActor 实验:我该如何解释这个结果?

  • 7

我尝试熟悉 Swift 并发,尤其是 MainActor。

我为自己制作了这个演示课程:

@MainActor
class ThreadsDemo {
  let range1000 = 0.. < 1000
  var randomNumber = 0

  init() {
    randomNumber = Int.random(in: range1000)
  }

  func modifyRandomNumber() async {
    print("2. isMain: \(Thread.isMainThread)")
    let newRandomNumber = Int.random(in: range1000)
    print("Generated random-number -> \(newRandomNumber)")
    Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false) {
      _ in
        print("4. isMain (within wait): \(Thread.isMainThread)")
    }
    print("5. isMain: \(Thread.isMainThread)")
    randomNumber = newRandomNumber
  }
}

调用ThreadDemo方法:

.task {
  print("1. isMain: \(Thread.isMainThread)")
  print("Initial random-number -> \(threadsDemo.randomNumber)")
  await threadsDemo.modifyRandomNumber()
  print("Modified random-number -> \(threadsDemo.randomNumber)")
  print("6. isMain: \(Thread.isMainThread)")
}

结果:

1. isMain: true
Initial random-number -> 455
2. isMain: true
Generated random-number -> 578
5. isMain: true
Modified random-number -> 578
6. isMain: true
4. isMain (within wait): true

显然,所有东西都在主线程上运行,甚至是预定计时器内的块。

我很困惑,因为我认为它会使用后台线程来防止 UI 冻结和无响应。

如果它无论如何都在主线程上运行所有内容,那么使用任务的目的是什么?

但我真正想弄清楚的是:

@MainActor 注释是否会导致在主线程上运行所有内容(所有可执行代码)还是只会导致始终在主线程上对状态(分配等)进行更改?

swift
  • 2 个回答
  • 59 Views
Martin Hope
ATL_DEV
Asked: 2025-04-25 07:20:01 +0800 CST

将数组元素与值进行比较会引发错误

  • 5

我不确定我做错了什么,但是当我执行下面的代码时:

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    let length = nums.count-1;

    for index1 in 0...length {
        let difference = target - nums[index1];
        print(target, difference, nums[index1])
        if (nums[index1] < difference) {
            for index2 in index1+1...length {
                if (nums[index2] == difference) {
                    return [index1, index2];
                }
            }
        }
    } 

    return [];
}

let summer = twoSum([-1,-2,-3,-4,-5], -8)

我收到以下错误:

Swift/ClosedRange.swift:347:致命错误:范围需要 lowerBound <= upperBound

有趣的是,如果我将 if 语句的条件更改为 nums[index1] <= target,它就不会崩溃。

swift
  • 2 个回答
  • 69 Views
Martin Hope
CalebK
Asked: 2025-04-24 15:35:25 +0800 CST

有没有办法在不设置内容最小框架的情况下为应用程序提供最小框架?

  • 6

此示例应用程序在 macOS 15.4 上运行时,打开和关闭侧边栏时会表现出奇怪的动画行为。

您需要做的就是删除该.frame(minWidth: 805, minHeight: 525)行以修复它,但这意味着您无法限制窗口的大小。

我希望我的应用程序有一个最小尺寸,但这defaultSize()行不通。

enum Page: String, Hashable {
    case settings = "Settings"
    case radio = "Radio"
    case connect = "Connect"
    
    var systemImageName: String {
        switch self {
        case .settings:
            return "gear"
        case .radio:
            return "radio"
        case .connect:
            return "dot.radiowaves.right"
        }
    }
}

struct ContentView: View {
    @State var pages = [Page.settings, Page.radio, Page.connect]
    
    var body: some View {
        NavigationSplitView {
            List(pages, id: \.self) { page in
                Label(page.rawValue.capitalized, systemImage: page.systemImageName)
            }
        } detail: {
            Text("Content")
        }
    }
}

@main
struct NavigationTestsApp: App {
    var body: some Scene {
        Window("Navigation", id: "H") {
            Group {
                ContentView()
                    // Without this line this animation bug does not happen
                    .frame(minWidth: 805, minHeight: 525)
            }
        }
    }
}

该漏洞的视频

swift
  • 1 个回答
  • 65 Views
Martin Hope
Youmate
Asked: 2025-04-24 07:56:48 +0800 CST

无法从非隔离上下文中引用 Actor 隔离属性“日志”

  • 6

我正在尝试学习 Swift 6。我一直面临的问题是,我无法读取(而不是尝试修改)来自的actor属性UI class。

是否可以在不添加额外存储属性或等待的情况下进行读取?

你能给我提供解决方案吗?

final actor Logger: Sendable {
    
    static let current = Logger()
    
    private(set) final var logs: [Int] = []
    
    private init() { }
    
    nonisolated var count: Int {
        
        return self.logs.count
    }
}

final class ViewController: NSViewController, NSTableViewDataSource {
   
    @IBOutlet weak var tableView: NSTableView!
     
    func numberOfRows(in tableView: NSTableView) -> Int {
        
        return Logger.current.count
    }
}

错误:

无法从非隔离上下文中引用 Actor 隔离属性“日志”

谢谢你!

swift
  • 1 个回答
  • 45 Views
Martin Hope
User95797654974
Asked: 2025-04-20 19:35:00 +0800 CST

为什么在 ForEach 中循环遍历数组的索引会降低滚动性能?

  • 8

我有一个大约 50k 个项目的大阵列,其中每个项目都符合可识别的要求。

我不会以任何方式改变数组,例如重新排列或任何其他方式。

如果我将其直接传递给 ForEach,列表滚动性能会比传递索引时明显更加流畅。

我意识到文档中提到了与每个细胞的结构特性有关的事情,但我无法理解为什么会出现这种情况。

ForEach(myArray, id: \.id) { item in
    MyRowView(item: item)
}

// Extremely choppy scroll
ForEach(myArray.indices, id: \.self) { index in
    MyRowView(item: myArray[index])
}
swift
  • 1 个回答
  • 94 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve