[英]Read NSArray of CGPoints in Swift
I have a function in an Objective-C class that returns an NSArray: 我在Objective-C类中有一个返回NSArray的函数:
- (NSArray *) myAwesomeFunction {
// Good stuff here
return array
}
Now I know that the members of this array are all NSValue
objects with a CGPoint
inside. 现在我知道该数组的成员都是内部带有
CGPoint
NSValue
对象。 This information is not available to Swift however, which infers the return type (correctly) as [AnyObject]!
但是,该信息不适用于Swift,它(正确地)将返回类型推断为
[AnyObject]!
Now when I try to cast the members of the array into an NSValue
I get a cast error as I should. 现在,当我尝试将数组的成员
NSValue
转换为NSValue
,我应该得到一个NSValue
转换错误。
let myArray = AnObjectiveCClass.myAwesomeFunction()
let myValue = myArray[0] as NSValue // Cast error since AnyObject cannot be cast to NSValue
This leaves me with a problem though, how can I access the contents of the array in my Swift class? 但是,这给我带来了一个问题,如何在我的Swift类中访问数组的内容? In the end I want to retrieve the CGPoint values inside of the array.
最后,我想在数组内部检索CGPoint值。
In my opinion, you can cast the the whole array to a [NSValue]
array: 我认为,您可以将整个数组转换为
[NSValue]
数组:
if let downcastNSValueArray = myArray as? [NSValue] {
let myValue = downcastNSValueArray[0]
}
You can simply add an Objective-C generics annotation to your method: 您可以简单地在方法中添加一个Objective-C 泛型注释 :
+ (NSArray<NSValue *> *) myAwesomeMethod {
// Good stuff here
return array;
}
Now Swift automatically infers the type: 现在,Swift自动推断类型:
let myArray = MyClass.myAwesomeMethod()
let myValue = myArray[0]
let myPoint = myValue.pointValue
Note that myArray
will be an implicitly-unwrapped optional ie an [NSValue]!
请注意,
myArray
将是一个隐式展开的可选值,即[NSValue]!
, so you could also add nullability annotations if you know myAwesomeMethod
won't ever return nil
. ,因此,如果您知道
myAwesomeMethod
永远不会返回nil
则也可以添加可空性注释 。 myValue
will be considered non-optional. myValue
将被视为非可选。 So the code above doesn't need any additional type handling to satisfy the compiler, but may still trigger runtime exceptions if myArray == nil
or if myArray.count < 1
. 因此,上面的代码不需要任何其他类型的处理即可满足编译器的要求,但如果
myArray == nil
或myArray.count < 1
,则仍可能触发运行时异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.