Swift中嵌套类型的扩展 [英] Extension of a nested type in Swift

查看:189
本文介绍了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 {
  }
}

我想通过扩展嵌套类(B)来添加功能;我尝试过:

I want to add functionality to the nested class (B) by extending it; I've tried:

extension A.B {
}

我得到'B'不是'A'的成员类型".

I get "'B' is not a member type of 'A'".

(我也尝试了一些不太合理的事情,但是为了避免尴尬,我将在这里省略它们.阅读Swift文档和谷歌搜索"swift嵌套类扩展"也没有给出答案.)

(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?

更新:

由于在user3441734中进行了尝试,因此在单个文件(或在Playground)中,此代码可以按预期工作!

This code works as expected when in a single file (or in a Playground), thanks to user3441734 for trying it out!

当这三个部分位于单独的文件中时,仍然无法正常工作,这可能是Swift编译器当前实现中的错误.我将向Apple提交错误报告.

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 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.

我发现的解决方法是转到目标设置,打开Build Phases.

The solution I've found is to go to your target settings, open Build Phases.

Compile Sources部分中,应将文件定义的位置放在嵌套类上方,而在扩展文件的位置应放在

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

修复将随Xcode 10.2一起提供

The fix will be shipping with Xcode 10.2

这篇关于Swift中嵌套类型的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆