Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 我可以在C中定义没有参数的构造函数吗?_Swift - Fatal编程技术网

Swift 我可以在C中定义没有参数的构造函数吗?

Swift 我可以在C中定义没有参数的构造函数吗?,swift,Swift,我有一个C代码: static __inline__ __attribute__((__always_inline__)) __attribute((swift_name("Test.init()"))) test_t test_init(void) { /* ... */ } 和测试Swift代码: let test = Test() 代码已编译,但函数test_init未调用 如果我添加test参数并与他一起调用init,我的方法*test\u init*将被调用。对于从C导入的结构,编

我有一个C代码:

static __inline__ __attribute__((__always_inline__))
__attribute((swift_name("Test.init()")))
test_t test_init(void) { /* ... */ }
和测试Swift代码:

let test = Test()
代码已编译,但函数test_init未调用


如果我添加test参数并与他一起调用init,我的方法*test\u init*将被调用。

对于从C导入的结构,编译器将创建一个
init()
初始值设定项,该初始值设定项不带参数,并将所有成员设置为零。比如说

__attribute((swift_name("Test")))
typedef struct {
    int a;
} test_t;
输入到Swift作为

public struct Test {
    public var a: Int32
    public init()
    public init(a: Int32)
}
正如Xcode中的“导航->跳转到生成的接口”所示

可以在C中创建其他init方法,但不能替换 现有的init方法。 (有人可能会说,编译器至少应该警告 C函数与SWIFT名称“Test.In()”将在SWIFT中被忽略,因此您可以考虑提交一个bug报告。 如果您想定义另一个在C中不带参数的init方法 然后必须给它一个伪
Void
参数:

__attribute((swift_name("Test.init(v:)")))
static __inline__ __attribute__((__always_inline__))
test_t test_init(void) {
    test_t t = { 3 };
    return t;
}
并称之为

let test = Test(v: ())
print(test) // Test(a: 3)

为什么默认init会覆盖我的实现?为什么不警告/错误?@qRoC:您只能通过子类化重写方法,不能通过扩展重写方法,也不能对结构重写方法。(假设您可以定义自己的
String.init
code来覆盖默认的初始值设定项…)-但是一个警告是合适的,我不能告诉您为什么不发布它。我在翻译级别上讲了“覆盖”,而不是多态性。好的,0044-不支持作为静态方法或init导入