gpt4 book ai didi

objective-c - 如何在 objective c 中使用具有泛型类型的 swift 类

转载 作者:IT王子 更新时间:2023-10-29 05:50:12 26 4
gpt4 key购买 nike

我有以下带有 NumericType T 的 swift 类。

@objc class MathStatistics<T: NumericType> : NSObject {
var numbers = [T]()

func sum() -> T? {
if numbers.count == 0 {
return nil
}

var sum = T(0)

for value in numbers {
sum = sum + value
}
return sum
}
}

在 swift 中初始化类对象如下:

let statistics = MathStatistics<Double>()

如何在 Objective C 中初始化同一个对象?下面这行没有设置数字类型T。

MathStatistics *stats = [[MathStatistics alloc] init];

最佳答案

你不能。如 documentation 中所列:

You’ll have access to anything within a class or protocol that’smarked with the @objc attribute as long as it’s compatible withObjective-C. This excludes Swift-only features such as those listedhere:

  • Generics
  • Tuples
  • Enumerations defined in Swift
  • Structures defined in Swift
  • Top-level functions defined in Swift
  • Global variables defined in Swift
  • Typealiases defined in Swift
  • Swift-style variadics
  • Nested types
  • Curried functions

您必须在类里面摆脱泛型。然后就可以在 Objective-C 中使用了

关于objective-c - 如何在 objective c 中使用具有泛型类型的 swift 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361848/

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