gpt4 book ai didi

ios - 强类型集合中为空?

转载 作者:行者123 更新时间:2023-11-29 11:45:13 25 4
gpt4 key购买 nike

我有一个强类型集合:

NSMutableArray<SupportClass *> *_items;

我需要将一个类似null 的对象放入其中。当您需要它与 ObjC 中的非类型化集合一起使用时 - 您可以使用 [NSNull null] object:

[_items replaceObjectAtIndex:index withObject:[NSNull null]];

但是对于键入的,我在该行收到以下警告:

Incompatible pointer types sending 'NSNull * _Nonnull' to parameter of type 'SupportClass * _Nonnull'

我理解为什么此示例中混合使用类型化集合和[NSNull null] 对象会出现警告。

什么是拥有具有编译时类型检查的强类型集合,同时能够将类似 null 的对象放入其中的正确方法?

最佳答案

I have a strongly typed collection:

NSMutableArray<SupportClass *> *_items;

合并您的两条评论:

But [the majority of] programming languages known to me allows to have a typed collection with compile time type checks and at the same time being able to put null objects into it. So I'm just looking for a way to do the same with ObjC.

你面临的麻烦是因为你正在使用最近添加的 Objective-C 来改进与 Swift 的交互工作,而 Swift 不允许你以这种方式将空值混合到你的“强类型集合”中。

Swift模型一般是将你习惯的“reference or null”模型替换为“non-null reference and optional”模型。在 Swift 中引用 SomeClassType是非空的,而类型 SomeClassType?Optional<SomeClassType> 的简写. Optional类型有两种情况:.none.some(v) , Swift 允许您测试 .none通过与 nil 比较.

Swift 并没有发明这个模型,(像语言的大部分部分一样)它是从其他语言继承而来的,就像许多函数式语言,它们是这种标记联合.

My question is: Which one is the preferred to deal with the issue from the experienced ObjC developer point of view?

使用 NSNull ,正如您所尝试的那样。这是 Apple 推荐的方式,也是 NSNull存在理由 ,但可以追溯到 Apple 引入轻量级泛型以帮助连接 Obj-C 和 Swift 之前。

如何在后轻量级泛型世界中使用“引用或空”模型?我认为您知道大多数替代方案,它们包括:

  • 不要。要么不要在 Obj-C 中使用强类型集合,要么按照 Swift 模型使用它们。
  • 使用 Swift。如果你想要静态强类型而不是运行时类型,请使用基于它的语言。
  • 使用子类。覆盖每个方法/属性以抛出非法使用 null 异常。添加 isNull谓词。等
  • 使用可区分的对象。不喜欢继承,然后只需创建一个类的唯一实例来充当 null 案例。添加适当的方法/属性来支持它。
  • 构建您自己的 Optional在 Obj-C 中。
  • 突破纸墙。轻量级泛型确实是标准集合之上的薄纸层,只是 break through it如果必须的话。
  • 等等

没有单一的“正确方法”可以解决您的问题。查看您的设计,确定“空引用”模型是否是关键,选择适合您情况的解决方案。

HTH

关于ios - 强类型集合中为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com