Perfect ICONV 简体中文

Get Involed with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 4.1 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

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)")
}

快速开始

Swift Package Manager

向 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 有几种编码转换的快捷方式

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

更多信息

有关 Perfect 项目的更多信息,请访问 perfect.org