How to implement Sequence (to enable Swift for-in syntax) from Objective-C?

I am writing an API in Objective-C and would like it to play well in Swift. I'm having trouble working with the for..in syntax. I think I need to implement the protocol Sequence, but I can not find examples made using Objective-C. Only the link Sequencegives me error: no type or protocol named 'Sequence'. Is there special #importaccess to it or something else?

I tried to implement the NSFastEnumeration protocol, thinking it would magically convert to Sequencein Swift, but that didn't work.

///// Obj-C Code
@interface Foo : NSObject<NSFastEnumeration>
...
@end

///// Swift Code
var foo: Foo = Foo()

// ERROR: Type 'Foo' does not conform to protocol 'Sequence'
for y in foo {
    print("Got a y.")
}

EDIT : It looks like inheritance from NSEnumerator brings me closer, but doesn't work:

///// Obj-C Code
@interface Foo : NSEnumerator<NSString *>
...
@end

///// Swift Code
// ERROR: 'NSFastEnumerationIterator.Element' (aka 'Any') is not convertible to 'String'
for y: String in foo {
    print("Got \(y)")
}

2: : https://bugs.swift.org/browse/SR-2801

+4
1

Foundation , NSFastEnumeration, Swift Sequence... .

- ObjC Swift NSFastEnumerationIterator:

extension Foo: Sequence {
    public func makeIterator() -> NSFastEnumerationIterator {
        return NSFastEnumerationIterator(self)
    }
}

NSFastEnumerationIterator ( ObjC) , , , . , ( ):

var foo: Foo = Foo()
for y in foo {
    print("Got a y.")
}

... y Any. foo, :

for y in foo where y is String {
    print("Got \(y)")
}

, ObjC, , - " Objective-C ", SE-0057. - ObjC .

+2

Source: https://habr.com/ru/post/1656149/


All Articles