* IDE:XCODE 6 beta3
*语言:Swift + Objective C
这是我的代码。
目标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
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)
}
}
}
我想要以下结果:
1 GET 3 4 GET 6 7 8 9 GET
但是,我的代码给了我错误
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
我认为此代码不完整。 但我无法找到解决方案 帮助我T T
答案 0 :(得分:18)
在Obj-C中,objectAtIndex:2如下所示:
[self.myArray ObjectAtIndex:2]
在Swift objectAtIndex:2中看起来像这样:
self.myArray[2]
答案 1 :(得分:1)
我使用以下方法模拟了你的数组:
NSArray * someArray() {
return @[@2, @5, @10];
}
您的代码在 Xcode 6 Beta 3
中编译并运行没有问题但是,您的代码无法执行您想要的操作,因为它会打印10 * target.count
个数字
正确地说,它应该是
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)
}
}
甚至更好
let target = arrayTest.getArray() as [Int]
for index in 1...10 {
if (contains(target, index)) {
println("GET")
} else {
println(index)
}
}