Unstringify
☝️ 是什么?
unstringify
(CLI):为强类型本地化字符串生成代码的工具。Unstringified
(模块):强类型本地化字符串静态源代码。
🤔 为什么?
它使您的本地化字符串代码
- 在编译时进行检查,
- 强类型,
- 由Xcode自动补全。
🛠 怎么做?
安装
安装Unstringify有多种方法
- 通过CocoaPods
- 通过Swift 包管理器
- 其他方式
- 下载最新版本的ZIP文件(仅推荐需要master分支功能或想要测试PR的情况)
- 通过Mint(系统范围内安装)
- 从源编译(仅推荐需要master分支功能或想要测试PR的情况)
CocoaPods
将unstringify
规范添加到您的Podfile
pod 'Unstringify'
将Unstringified
作为包含字符串文件的模块的podspec中的依赖项
s.dependency 'Unstringified'
注意: 如果您的应用不是模块化的,只需将pod 'Unstringified'
添加到您的Podfile
中即可。
添加一个生成Unstringified
枚举代码的构建阶段
"$PODS_ROOT/Unstringify/unstringify" "$SRCROOT/path/to/module/en.lproj/Localizable.strings" "$SRCROOT/path/to/module/Unstringified.generated.swift"
Swift包管理器
在您的Package.swift
文件中声明Unstringify
依赖
dependencies: [
.package(url: "https://github.com/metrolab/Unstringify", from: "0.1.0"),
]
执行CLI,传递参数为输入字符串文件和输出文件路径
swift run unstringify path/to/module/en.lproj/Localizable.string path/to/module/Unstringified.generated.swift
为了使用生成的文件,您需要将Unstringified
链接到包含生成文件和原始字符串文件的模块
使用方法
CLI使用
$ ./unstringify
Usage: ./unstringify inputPath outputPath [templatePath]
注意: templatePath
是可选的。
输入(例如:en.lproj/Localizable.strings
)
"form_title" = "Contact";
"form_name_field" = "Name:";
"form_name_field_max_length" = "Maximum length is %d characters.";
"form_name_field_description" = "Enter your <b>full name</b>";
输出(例如:Unstringified.generated.swift
)
// Generated by Unstringify.
// DO NOT EDIT!
import Foundation
import Unstringified
private final class _Unstringified {}
extension Unstringified {
public var localizableStringsTableName: String? {
return nil
}
public var localizableStringsBundle: Bundle? {
let _UnstringifiedBundle = Bundle(for: _Unstringified.self)
guard _UnstringifiedBundle.bundleIdentifier != Bundle.main.bundleIdentifier else {
return Bundle.main
}
let bundleURL = _UnstringifiedBundle.bundleURL
let bundleName = bundleURL.lastPathComponent
let resource = (bundleName as NSString).deletingPathExtension
guard let path = _UnstringifiedBundle.path(forResource: resource, ofType: "bundle") else {
return nil
}
return Bundle(path: path)
}
}
public enum Text: String, Unstringified {
public typealias StringType = String
case form_title, form_name_field
}
public enum Format: Unstringified {
public typealias StringType = String
case form_name_field_max_length(Int)
}
public enum RichText: String, Unstringified {
public typealias StringType = NSAttributedString
case form_name_field_description
}
public enum RichFormat: Unstringified {
public typealias StringType = NSAttributedString
case 👻(Void)
}
自定义
您可以通过扩展它们来自定义每个枚举(Text
、Format
、RichText
、RichFormat
)的localizableStringsTableName
和localizableStringsBundle
。
extension Text {
public var localizableStringsTableName: String? {
return "xxx"
}
}
模板
您还可以通过使用自定义模板来自定义生成的代码。
您的模板必须包含以下变量
- $KEYS_ARRAY
- $FORMATED_KEYS_ARRAY
- $RICH_KEYS_ARRAY
- $FORMATED_RICH_KEYS_ARRAY
示例
查看示例目录。
📖 许可证
Unstringify遵循MIT许可证发布。有关详细信息,请参阅LICENSE
。