简体   繁体   中英

Is there a way to expose an NSArray<NSValue> of CGPoint as [CGPoint] to Swift?

I have this property:

@property (nonatomic) NSArray<NSValue *> *vertices;

where the vertices are of type CGPoint .

I know swift has some convenient language features such as NS_SWIFT_NAME to change the function names, but I wonder if there is a way to expose that property as [CGPoint] type in Swift.

I am asking on how to do this in objective-c syntax, how to create an objective-c API that exposes "vertices" as a [CGPoint] when used in Swift.

Thanks.

As per my understanding you need above CGPoint array in Obj-C so you can use CGPoint array like this :

self.vertices = @[[NSValue valueWithCGPoint:CGPointMake(0, 10)],
                      [NSValue valueWithCGPoint:CGPointMake(10, 20)]];

for get back that point :

CGPoint pointValue = [self.vertices[0] CGPointValue];

Hope this will helps.

You cannot write, in Obj-C, a property that is of type [CGPoint] in Swift.

What you can do is annotate your vertices property with NS_REFINED_FOR_SWIFT . This will expose it to Swift as a property named __vertices instead. Now you can write an extension on your class in Swift that provides its own var vertices: [CGPoint] computed property. It might look like

var vertices: [CGPoint] {
    return __vertices.map({ $0.cgPointValue })
}

The downside to this approach is every time you access the vertices property from Swift it will have to allocate a brand new array. But there's not really any way around that if you want to expose a [CGPoint] (besides trying to see if you can implement any sort of caching behavior, where you only create the new [CGPoint] if the original NSArray<NSValue *> changed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM