Skip to content

Commit

Permalink
Swift 3 support
Browse files Browse the repository at this point in the history
  • Loading branch information
hongxinhope committed Sep 20, 2016
1 parent d347d19 commit 4be39f6
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 118 deletions.
12 changes: 11 additions & 1 deletion HanziPinyin.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,12 @@
D395A11C1CC244BB00B76FB7 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0730;
LastUpgradeCheck = 0800;
ORGANIZATIONNAME = Teambition;
TargetAttributes = {
D395A1241CC244BB00B76FB7 = {
CreatedOnToolsVersion = 7.3;
LastSwiftMigration = 0800;
};
};
};
Expand Down Expand Up @@ -188,8 +189,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
Expand Down Expand Up @@ -237,8 +240,10 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
Expand All @@ -258,6 +263,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
Expand All @@ -269,6 +275,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
Expand All @@ -280,13 +287,15 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
D395A12F1CC244BB00B76FB7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
Expand All @@ -297,6 +306,7 @@
PRODUCT_BUNDLE_IDENTIFIER = Teambition.HanziPinyin;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
};
name = Release;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
22 changes: 11 additions & 11 deletions HanziPinyin/HanziPinyin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,34 +15,34 @@ internal struct HanziCodePoint {

internal struct HanziPinyin {
internal static let sharedInstance = HanziPinyin()
internal private(set) var unicodeToPinyinTable: [String: String] = [:]
internal fileprivate(set) var unicodeToPinyinTable = [String: String]()

init() {
unicodeToPinyinTable = initializeResource()
}

internal static func pinyinArrayWithCharCodePoint(charCodePoint: UInt32, outputFormat: PinyinOutputFormat = PinyinOutputFormat.defaultFormat) -> [String] {
func isValidPinyin(pinyin: String) -> Bool {
internal static func pinyinArray(withCharCodePoint charCodePoint: UInt32, outputFormat: PinyinOutputFormat = .default) -> [String] {
func isValidPinyin(_ pinyin: String) -> Bool {
return pinyin != "(none0)" && pinyin.hasPrefix("(") && pinyin.hasSuffix(")")
}

let codePointHex = String(format: "%x", charCodePoint).uppercaseString
guard let pinyin = HanziPinyin.sharedInstance.unicodeToPinyinTable[codePointHex] where isValidPinyin(pinyin) else {
let codePointHex = String(format: "%x", charCodePoint).uppercased()
guard let pinyin = HanziPinyin.sharedInstance.unicodeToPinyinTable[codePointHex], isValidPinyin(pinyin) else {
return []
}

let leftBracketRange = pinyin.rangeOfString("(")!
let rightBracketRange = pinyin.rangeOfString(")")!
let processedPinyin = pinyin.substringWithRange(leftBracketRange.endIndex..<rightBracketRange.startIndex)
let pinyinArray = processedPinyin.componentsSeparatedByString(",")
let leftBracketRange = pinyin.range(of: "(")!
let rightBracketRange = pinyin.range(of: ")")!
let processedPinyin = pinyin.substring(with: leftBracketRange.upperBound..<rightBracketRange.lowerBound)
let pinyinArray = processedPinyin.components(separatedBy: ",")

let formattedPinyinArray = pinyinArray.map { (pinyin) -> String in
return PinyinFormatter.formatPinyin(pinyin, withOutputFormat: outputFormat)
return PinyinFormatter.format(pinyin, withOutputFormat: outputFormat)
}
return formattedPinyinArray
}

internal static func isHanzi(charCodePoint: UInt32) -> Bool {
internal static func isHanzi(ofCharCodePoint charCodePoint: UInt32) -> Bool {
return charCodePoint >= HanziCodePoint.start && charCodePoint <= HanziCodePoint.end
}
}
46 changes: 23 additions & 23 deletions HanziPinyin/HanziPinyinResource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,28 @@ private struct CacheKeys {

internal extension HanziPinyin {
internal func initializeResource() -> [String: String] {
if let cachedPinyinTable = HanziPinyin.cachedObjectForKey(CacheKeys.unicodeToPinyin) as? [String: String] {
if let cachedPinyinTable = HanziPinyin.cachedObject(forKey: CacheKeys.unicodeToPinyin) as? [String: String] {
return cachedPinyinTable
} else {
let resourceBundle = NSBundle(identifier: "Teambition.HanziPinyin") ?? NSBundle.mainBundle()
guard let resourcePath = resourceBundle.pathForResource("unicode_to_hanyu_pinyin", ofType: "txt") else {
let resourceBundle = Bundle(identifier: "Teambition.HanziPinyin") ?? Bundle.main
guard let resourcePath = resourceBundle.path(forResource: "unicode_to_hanyu_pinyin", ofType: "txt") else {
return [:]
}

do {
let unicodeToPinyinText = try NSString(contentsOfFile: resourcePath, encoding: NSUTF8StringEncoding) as String
let textComponents = unicodeToPinyinText.componentsSeparatedByString("\r\n")
let unicodeToPinyinText = try String(contentsOf: URL(fileURLWithPath: resourcePath))
let textComponents = unicodeToPinyinText.components(separatedBy: "\r\n")

var pinyinTable = [String: String]()
for pinyin in textComponents {
let components = pinyin.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let components = pinyin.components(separatedBy: .whitespaces)
guard components.count > 1 else {
continue
}
pinyinTable.updateValue(components[1], forKey: components[0])
}

HanziPinyin.cacheObject(pinyinTable, forKey: CacheKeys.unicodeToPinyin)
HanziPinyin.cache(pinyinTable, forKey: CacheKeys.unicodeToPinyin)
return pinyinTable
} catch _ {
return [:]
Expand All @@ -45,15 +45,15 @@ internal extension HanziPinyin {
}

internal extension HanziPinyin {
private static var pinYinCachePath: String? {
guard let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first else {
fileprivate static var pinYinCachePath: String? {
guard let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
return nil
}

let pinYinCachePath = NSString(string: documentsPath).stringByAppendingPathComponent("PinYinCache")
if !NSFileManager.defaultManager().fileExistsAtPath(pinYinCachePath) {
let pinYinCachePath = NSString(string: documentsPath).appendingPathComponent("PinYinCache")
if !FileManager.default.fileExists(atPath: pinYinCachePath) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(pinYinCachePath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default.createDirectory(atPath: pinYinCachePath, withIntermediateDirectories: true, attributes: nil)
} catch {
print("create pinYin cache path error: \(error)")
return nil
Expand All @@ -62,34 +62,34 @@ internal extension HanziPinyin {
return pinYinCachePath
}

private static func pinYinCachePathForKey(key: String) -> String? {
fileprivate static func pinYinCachePath(forKey key: String) -> String? {
guard let pinYinCachePath = pinYinCachePath else {
return nil
}
return NSString(string: pinYinCachePath).stringByAppendingPathComponent(key)
return NSString(string: pinYinCachePath).appendingPathComponent(key)
}

private static func cacheObject(object: NSCoding, forKey key: String) {
let archivedData = NSKeyedArchiver.archivedDataWithRootObject(object)
guard let cachePath = pinYinCachePathForKey(key) else {
fileprivate static func cache(_ object: Any, forKey key: String) {
let archivedData = NSKeyedArchiver.archivedData(withRootObject: object)
guard let cachePath = pinYinCachePath(forKey: key) else {
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
DispatchQueue.global(qos: .default).async {
do {
try archivedData.writeToFile(cachePath, options: .AtomicWrite)
try archivedData.write(to: URL(fileURLWithPath: cachePath), options: .atomicWrite)
} catch let error {
print("cache object error: \(error)")
}
}
}

private static func cachedObjectForKey(key: String) -> NSCoding? {
guard let cachePath = pinYinCachePathForKey(key) else {
fileprivate static func cachedObject(forKey key: String) -> Any? {
guard let cachePath = pinYinCachePath(forKey: key) else {
return nil
}
do {
let data = try NSData(contentsOfFile: cachePath, options: [])
return NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSCoding
let data = try Data(contentsOf: URL(fileURLWithPath: cachePath), options: [])
return NSKeyedUnarchiver.unarchiveObject(with: data)
} catch _ {
return nil
}
Expand Down
26 changes: 13 additions & 13 deletions HanziPinyin/PinyinFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,30 @@
import Foundation

internal struct PinyinFormatter {
internal static func formatPinyin(pinyin: String, withOutputFormat format: PinyinOutputFormat) -> String {
internal static func format(_ pinyin: String, withOutputFormat format: PinyinOutputFormat) -> String {
var formattedPinyin = pinyin

switch format.toneType {
case .None:
formattedPinyin = formattedPinyin.stringByReplacingOccurrencesOfString("[1-5]", withString: "", options: .RegularExpressionSearch, range: formattedPinyin.startIndex..<formattedPinyin.endIndex)
case .ToneNumber:
case .none:
formattedPinyin = formattedPinyin.replacingOccurrences(of: "[1-5]", with: "", options: .regularExpression, range: formattedPinyin.startIndex..<formattedPinyin.endIndex)
case .toneNumber:
break
}

switch format.vCharType {
case .VCharacter:
formattedPinyin = formattedPinyin.stringByReplacingOccurrencesOfString("u:", withString: "v")
case .UUnicode:
formattedPinyin = formattedPinyin.stringByReplacingOccurrencesOfString("u:", withString: "ü")
case .UAndColon:
case .vCharacter:
formattedPinyin = formattedPinyin.replacingOccurrences(of: "u:", with: "v")
case .uUnicode:
formattedPinyin = formattedPinyin.replacingOccurrences(of: "u:", with: "ü")
case .uAndColon:
break
}

switch format.caseType {
case .Lowercase:
formattedPinyin = formattedPinyin.lowercaseString
case .Uppercase:
formattedPinyin = formattedPinyin.uppercaseString
case .lowercase:
formattedPinyin = formattedPinyin.lowercased()
case .uppercase:
formattedPinyin = formattedPinyin.uppercased()
}

return formattedPinyin
Expand Down
18 changes: 9 additions & 9 deletions HanziPinyin/PinyinOutputFormat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,27 @@
import Foundation

public enum PinyinToneType {
case None
case ToneNumber
case none
case toneNumber
}

public enum PinyinVCharType {
case VCharacter
case UUnicode
case UAndColon
case vCharacter
case uUnicode
case uAndColon
}

public enum PinyinCaseType {
case Lowercase
case Uppercase
case lowercase
case uppercase
}

public struct PinyinOutputFormat {
public var toneType: PinyinToneType
public var vCharType: PinyinVCharType
public var caseType: PinyinCaseType

public static var defaultFormat: PinyinOutputFormat {
return PinyinOutputFormat(toneType: .None, vCharType: .VCharacter, caseType: .Lowercase)
public static var `default`: PinyinOutputFormat {
return PinyinOutputFormat(toneType: .none, vCharType: .vCharacter, caseType: .lowercase)
}
}
Loading

0 comments on commit 4be39f6

Please sign in to comment.