Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use objectAtIndex in swift

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

Here is my code.

Objective C Code

@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

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 T T

like image 558
SaeHyun Kim Avatar asked Jul 11 '14 11:07

SaeHyun Kim


2 Answers

In Obj-C, objectAtIndex: 2 looks like this:

[self.myArray ObjectAtIndex:2]

In Swift objectAtIndex: 2 looks like this:

self.myArray[2]
like image 153
iOSAppGuy Avatar answered Oct 10 '22 08:10

iOSAppGuy


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

However, your code doesn't do what you want because it prints 10 * target.count numbers

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)
    }
}
like image 36
Sulthan Avatar answered Oct 10 '22 08:10

Sulthan