【问题标题】:OC call one swift function which returns an int array, but can not accept its element with an int variableOC 调用一个 swift 函数,它返回一个 int 数组,但不能接受带有 int 变量的元素
【发布时间】:2015-05-05 01:59:03
【问题描述】:

我编写了一个 swift 函数,它返回一个 int 数组并在 Objective-c 中调用它。但是我不能将返回数组的元素分配给 int 变量。 (在swift中TotalRoute是一个int数组)

这是GetRoute类中的函数

func returnTotalRouteX()->[Int]{
    println("call returnTotalRouteX")
    var routeX = [Int]()
    for item in totalRoute{
        routeX.append(nodeData[item]!.xPosition)
    }
    println(totalRoute)
    println(routeX)
    return routeX
}

然后我在objective-c中调用它

    GetRoute *h = [[GetRoute alloc] init];

if (h.returnTotalRouteX.count == 0) {
    NSLog(@"it is empty");
}
else{
    NSLog(@"%@",h.returnTotalRouteX);
    NSLog(@"%@",h.returnTotalRouteX[0]);
    NSLog(@"it is not empty");
}

我只能写 NSLog(@"%@",h.returnTotalRouteX[0]);。如果我写 NSLog(@"%d",h.returnTotalRouteX[0]);或者我将 h.returnTotalRouteX[0] 分配给一个 int 变量,答案不是我想要的。如何获取 int 值?

【问题讨论】:

  • 你有没有试过拆箱,即[h.returnTotalRouteX[0] intValue]
  • 是的!它符合您的建议!谢谢!

标签: objective-c swift nsarray


【解决方案1】:

您需要通过调用numberWithIntNSNumber 拆箱 转换为原始int,因此在您的情况下为[h.returnTotalRouteX[0] intValue]。当您使用%@ 模式登录时它起作用的原因是它正在调用它的字符串格式化程序。

在 OOP 中,装箱是在引用类型中存储原始类型。 拆箱是相反的过程。

某些语言(例如 C#)按照惯例自动提供装箱和/或拆箱功能。所以以下在 C# 中完全没问题:

int unBoxed = 420;
Object boxed = unBoxed;
int unUnBoxed = (int)unBoxed;

但是,Objective-C 不会为您执行此操作。所以在 Objective-C 中也是这样的:

int unBoxed = 420;
NSNumber *boxed = [NSNumber numberWithInt:unBoxed];
int unUnBoxed = [boxed intValue];

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多