gpt4 book ai didi

objective-c - for in 循环中的类型安全

转载 作者:太空狗 更新时间:2023-10-30 03:53:53 30 4
gpt4 key购买 nike

我已经在 objective-c 中尝试类型安全一段时间了。我想我得到了一些,但我想知道以下是否可能。

NSMutableArray <NSNumber *> *x = [NSMutableArray new];
[x addObject:@14];
[x addObject:@"s"]; // <--- Gives warning, good!

for (NSUInteger i = 0; i < x.count; i++) {
NSString *s = [x objectAtIndex:i]; // <-- Gives warning, good!
}

NSString *d = x[0]; // <-- Gives warning, good!


//but
for (NSString *s in x) // <-- expected warning but didn't get it
NSLog(@"%@", [s stringByAppendingString:@"s"]; // <-- no warning just run time error

所以我的问题是,当使用不正确的对象时,for in 循环是否会发出警告。我想使用 for in 因为它速度快并且隐藏了实现细节。

最佳答案

问题来了。

大多数 NSArray/NSMutableArray 方法,例如 addObject:objectAtIndexedSubscript:(允许现代 [index] 语法)获取或返回 ObjectType 值。 ObjectType 是一个特殊的指示符,表示为数组指定“使用泛型类型”。

快速枚举来自 NSFastEnumeration 协议(protocol)及其 countByEnumeratingWithState:objects:count: 方法。不幸的是,objects 参数是 id 的 C 数组。它不使用 ObjectType。由于对象的类型为 id,因此编译器无法像对 NSArray 的其他方法那样进行任何类型检查。

关于objective-c - for in 循环中的类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954969/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com