2014-07-11 8 views
6

* IDE: XCODE 6 beta3
* Lingua: Swift + Objective CCome usare objectAtIndex in rapida

Ecco il mio codice.

Objective C Codice

@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) 
     } 
    } 
} 

voglio il seguente risultato:

1 GET 3 4 GET 6 7 8 9 GET 

Ma, il mio codice mi dà l'errore

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 

Penso che questo codice sia incompleto. Ma non riesco a trovare la soluzione.
Aiutami TT

+0

" Trasmissione dinamica rapida fallita "il tuo array non contiene' Int', prova a stampare l'array –

+0

Probabilmente contiene 'NSNumber' in distanze. – Sulthan

risposta

16

In Obj-C, objectAtIndex: 2 si presenta così:

[self.myArray ObjectAtIndex:2] 

In Swift objectAtIndex: 2 si presenta così:

self.myArray[2] 
1

Ho simulato la matrice utilizzando:

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

e il codice compilato ed eseguito senza problemi Xcode 6 Beta 3

Tuttavia, il codice non fa quello che vuoi perché stampa 10 * target.count numeri

Correttamente, dovrebbe essere

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) 
    } 
} 

o meglio ancora

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

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

1. let target = arrayTest.getArray() come [Int] -> 'AnyObject' non è identico a 'Int' 2. if (contains (target, index)) {-> 'NSNumber' non è un sottotipo di 'S.GeneratorType.Element -> L' –

+0

@SaeHyunKim Sei sicuro di utilizzare l'ultima versione beta? Beta 3? – Sulthan

+0

La mia versione xcode è 'Versione 6.0 (6A254o)' (Beta 3) –