I have a main class, also providing a namespace:
class A { }
and a nested class added via an extension (all for the sake of using separate files):
extension A { class B { } }
I want to add functionality to the nested class (B) by extending it; I've tried:
extension A.B { }
I get "'B' is not a member type of 'A'".
(I've also tried some less reasonable things but I will omit them here to avoid embarrassment. Reading Swift docs and Googling for "swift nested class extension" have not yielded an answer either.)
Any idea if and how that could be accomplished?
UPDATE:
This code works as expected when in a single file (or in a Playground), thanks to user3441734 for trying it out!
Still does not work when the 3 parts are in separate files, perhaps a bug in current implementation of the Swift compiler. I will submit a bug report to Apple.
It is not possible to subclass a struct in Swift, only classes can be subclassed. An extension is not a subclass, it's just adding additional functionality on to the existing struct , this is comparable to a category in Objective-C.
To accomplish this, Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support. To nest a type within another type, write its definition within the outer braces of the type it supports.
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C.
You see, although Swift's extensions let you add methods and computed properties to existing data types, they don't let you add stored properties.
It seems like this problem is related to SR-631. I've encountered similar a issue, I guess the complier is trying to process the file where you extend the nested class before the one where it's defined. Therefore you have this error saying that that A has no member B.
The solution I've found is to go to your target settings, open Build Phases
.
There, in Compile Sources
section you should put the file where you define the nested class above files where you extend it.
The fix will be shipping with Xcode 10.2
this works in my playground, as expected
class A { } extension A { class B { } } extension A.B { func foo() { print("print from extension A.B") } } let ab = A.B() ab.foo() // print from extension A.B
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With