Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

swift2 - Extension of a nested type in Swift

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

enter image description here

There, in Compile Sources section you should put the file where you define the nested class above files where you extend it.

Update

The fix will be shipping with Xcode 10.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...