Swift:访问作为对象的C结构成员 我现在所拥有的:
在我的应用程序中,我有一个保存颜色的全局C结构:Swift:访问作为对象的C结构成员 我现在所拥有的:,c,swift,pointers,struct,foundation,C,Swift,Pointers,Struct,Foundation,在我的应用程序中,我有一个保存颜色的全局C结构: //Colors.h extern struct MYColors *appColors; struct MYColors { CGColorRef appBackgroundColor; // ...Lots more colors follow }; 以及匹配的实现文件: //Colors.m struct MYColors *appColors = calloc(1, sizeof(struct MYColors))
//Colors.h
extern struct MYColors *appColors;
struct MYColors
{
CGColorRef appBackgroundColor;
// ...Lots more colors follow
};
以及匹配的实现文件:
//Colors.m
struct MYColors *appColors = calloc(1, sizeof(struct MYColors));
appColors->appBackgroundColor = CGColorCreateGenericRGB(23.0f/255.0f, 24.0f/255.0f, 26.0f/255.0f, 1.0f);
这使我能够集中所有应用程序的颜色。在各种自定义视图中,我在Objective-C中编写了如下代码:
- (void) updateLayer {
someCGLayer.backgroundColor = appColors->appBackgroundColor;
}
我需要的是: 我正开始将此应用程序迁移到Swift,但我还不知道如何访问此C结构的导入版本。我看过很多关于简单结构的帖子,其中包含
int
,float
等
如果我有这个结构的全局实例(基本上是一个单实例),appColors
,我如何从Swift访问该结构的成员
我认为有效的方法是: 这是行不通的。斯威夫特声称,
MYColors
没有appBackgroundColor
:
let color: CGColor = UnsafePointer<MYColors>(appColors).appBackgroundColor
let-color:CGColor=UnsafePointer(appColors).appBackgroundColor
我还想也许我只需要像这样访问singleton:
let color: CGColor = UnsafePointer<MYColors>(MyModuleName.appColors!).appBackgroundColor
let-color:CGColor=UnsafePointer(MyModuleName.appColors!).appBackgroundColor
但这也不起作用。C声明
extern struct MYColors * appColors;
输入到Swift作为
public var appColors: UnsafeMutablePointer<MYColors>!
是
该值的类型为非托管因为Swift编译器不知道应该如何管理对象的内存。在您的情况下,调用方不负责释放对象,因此最终代码为:
let bgColor = appColors.pointee.appBackgroundColor.takeUnretainedValue()
有关非托管引用的详细信息,请参见
备注:如果appColors
和所有结构成员在访问时都保证为非空,则可以在界面中使用\u Nonnull
对其进行注释:
struct MYColors {
CGColorRef _Nonnull appBackgroundColor;
// ...
};
extern struct MYColors * _Nonnull appColors;
然后,Swift编译器将变量作为非可选变量而不是(隐式展开)可选变量导入。对于上下文:我创建一个包含所有CGColors的单例的原因有两个:(1)它允许我在数百个视图中分配每种颜色一次,而不是数千次从结构访问颜色实例,这比在每个绘图方法中不断创建颜色实例要快得多。(2) 我在macOS 10.11+上支持暗模式,当我的用户更改模式时,我只需重新创建此结构中的所有颜色,并告诉我的应用程序重新绘制它,这样我就可以快速更改应用程序的整个主题,我的视图不必担心它们处于暗模式还是亮模式。谢谢@MartinR!“指针”正是我需要的。
let bgColor = appColors.pointee.appBackgroundColor.takeUnretainedValue()
struct MYColors {
CGColorRef _Nonnull appBackgroundColor;
// ...
};
extern struct MYColors * _Nonnull appColors;