ICONV 的 Swift 类封装,灵感来自 Yasuhiro Hatta 的 Iconv 项目。 详情请参见 https://github.com/yaslab/Iconv。
此软件包使用 Swift Package Manager 构建,并且是 Perfect 项目的一部分。
import PerfectICONV
do {
let i = try Iconv()
let bytes:[UInt8] = [0xd6, 0xd0, 0xb9, 0xfa, 0x0a]
guard let cn = i.utf8(buf: bytes) else {
XCTFail("fault")
return
}//end guard
print(cn)
XCTAssertTrue(cn.hasPrefix("中国"))
}catch(let err) {
XCTFail("ERROR: \(err)")
}
向 Package.swift 添加依赖项
.Package(url: "https://github.com/PerfectSideRepos/Perfect-ICONV.git",
majorVersion:3)
将 iconv 库导入到您的源代码
import PerfectICONV
在转换编码之前,设置代码页
do {
let iconv = try Iconv(from: .GB2312, to: .UTF_8)
}catch(let err) {
/// something goes wrong here, e.g., invalid code page, etc.
}
注意:可以在此项目的源代码中找到代码页常量,关键字为 enum
public enum CodePage: String {
case US = "US"
case US_ASCII = "US-ASCII"
case CSASCII = "CSASCII"
case UTF_8 = "UTF-8"
case UTF8 = "UTF8"
...
}
PerfectICONV 有几种编码转换的快捷方式
iconv.utf8(bytes: [Int8])
或 iconv.utf8(bytes: [UInt8])
: 直接将有符号或无符号字节缓冲区从源代码页转换为 utf-8let bytes:[UInt8] = [0xd6, 0xd0, 0xb9, 0xfa, 0x0a]
guard let china = iconv.utf8(buf: bytes) else {
/// something wrong
}//end guard
// if ok, it will print "中国"
print(china)
iconv.convert(buf: [Int8]) -> [Int8]
或 iconv.convert(buf: [UInt8]) -> [UInt8]
: 将代码页从一个字节缓冲区转换为另一个let bytes:[UInt8] = [0xd6, 0xd0, 0xb9, 0xfa, 0x0a]
let chinaBytes = iconv.convert(buf: bytes)
// if nothing wrong, the chinaBytes is now an array of UInt8 which contains the expected encoding.
iconv.convert(buf: UnsafePointer<Int8>, length: Int) -> (UnsafeMutablePointer<Int8>?, Int)
: 类似于 Hatta 先生的 API 设计,从具有长度的指针转换源编码到目标元组。有关 Perfect 项目的更多信息,请访问 perfect.org。