简体   繁体   English

如何在swift中使用objectAtIndex

[英]How to use objectAtIndex in swift

*IDE: XCODE 6 beta3 * IDE:XCODE 6 beta3
*Language: Swift + Objective C *语言:Swift + Objective C

Here is my code. 这是我的代码。

Objective C Code 目标C代码

@implementation arrayTest
{
    NSMutableArray *mutableArray;
}
- (id) init {
    self = [super init];
    if(self) {
        mutableArray = [[NSMutableArray alloc] init];
    }
    return self;
}
- (NSMutableArray *) getArray {
          ...
    return mutableArray; // mutableArray = {2, 5, 10}
}

Swift Code SWIFT代码

var target = arrayTest.getArray() // target = {2, 5, 10} 

for index in 1...10 {
    for targetIndex in 1...target.count { // target.count = 3
        if index == target.objectAtIndex(targetIndex-1) as Int { 
            println("GET")
        } else {
            println(index)
        }
    }
}

I want the following result: 我想要以下结果:

1 GET 3 4 GET 6 7 8 9 GET

But, my code gives me the error 但是,我的代码给了我错误

libswift_stdlib_core.dylib`swift_dynamicCastObjCClassUnconditional:
0x107e385b0:  pushq  %rbp
...(skip)
0x107e385e4:  leaq   0xa167(%rip), %rax        ; "Swift dynamic cast failed"
0x107e385eb:  movq   %rax, 0x6e9de(%rip)       ; gCRAnnotations + 8
0x107e385f2:  int3   
0x107e385f3:  nopw   %cs:(%rax,%rax)

.

if index == target.objectAtIndex(targetIndex-1) as Int { 
// target.objectAtIndex(0) = 2 -> but type is not integer

I think this code is incomplete. 我认为这段代码不完整。 But I can't find the solution. 但我找不到解决方案。
Help me TT 帮我TT

In Obj-C, objectAtIndex: 2 looks like this: 在Obj-C中,objectAtIndex:2看起来像这样:

[self.myArray ObjectAtIndex:2]

In Swift objectAtIndex: 2 looks like this: 在Swift objectAtIndex:2中如下所示:

self.myArray[2]

I have simulated your array using: 我用以下方法模拟了你的数组:

NSArray * someArray() {
    return @[@2, @5, @10];
}

And your code compiles and runs without problems in Xcode 6 Beta 3 并且您的代码在Xcode 6 Beta 3中编译和运行没有问题

However, your code doesn't do what you want because it prints 10 * target.count numbers 但是,您的代码无法执行您想要的操作,因为它会打印10 * target.count数字

Correctly, it should be 应该是正确的

let target = arrayTest.getArray() as [Int]

for index in 1...10 {
    var found = false

    for targetIndex in indices(target) {
        if index == target[targetIndex] {
            found = true
            break
        }
    }

    if (found) {
        println("GET")
    } else {
        println(index)
    }
}

or even better 甚至更好

let target = arrayTest.getArray() as [Int]

for index in 1...10 {
    if (contains(target, index)) {
        println("GET")
    } else {
        println(index)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM