如何包含在Swift语言中

时间:2014-06-20 19:27:14

标签: ios objective-c swift

我有一个Objective-C类

#include <arpa/inet.h>

但是如何在Swift语言中包含它?

2 个答案:

答案 0 :(得分:1)

您不能直接在Swift源代码文件中包含C标头。而是在Objective C头文件中包含C头,并添加一个桥接头,其中包含Xcode项目所需的所有Objective C头。

答案 1 :(得分:0)

如果您导入<arpa/inet.h>FoundationDarwin中定义的某些功能可用。

但是,了解如何使用它们需要一些工作。您应该创建一个游乐场或使用命令行REPL进行实验。例如:

$ xcrun swift
"crashlog" and "save_crashlog" command installed, use the "--help" option for detailed help
"malloc_info", "ptr_refs", "cstr_refs", and "objc_refs" commands have been installed, use the "--help" options on these commands for detailed help.
Welcome to Swift!  Type :help for assistance.
  1> import Foundation
  2> inet_addr("10.0.1.1")
$R6: in_addr_t = {
  value = 16842762
}
  3> var a = in_addr(s_addr: 16842762)
a: in_addr = {
  s_addr = {
    value = 16842762
  }
}
  4> inet_netof(a)
$R7: in_addr_t = {
  value = 10
}
  5> 

您可能会发现处理C字符串的函数(如inet_ntoa)太难以处理。您可能更容易在Objective-C中编写一个包装类,为您感兴趣的每个<arpa/inet.h>函数提供一个类方法。类方法可以在原始C字符串和NSString之间进行转换秒。然后,您可以从Swift代码中调用此Objective-C包装器的类方法。