如果我用单数
unit
名创建值,则是自动语法协议 (https://www.swiftjectivec.com/morphology-in-ios-with-automatic-grammar-agreement/
)完美工作:
Effort(amount: 4, unit: "day").attributedString
“ 4天”
Effort(amount: 1, unit: "day").attributedString
“ 1天”
,但是,如果我用已经复数的字符串创建此结构,那么自动语法协议实际上不会将其变回单数:
Effort(amount: 1, unit: "days").attributedString
“ 1天”
有任何方法可以使它双向工作?我愿意重构此代码,即使这意味着它不会那么“优雅”,即,如果我必须手动编写拐点规则。动力:服务器已经以复数形式返回值,也最好使客户端完全不可知服务器响应。我正在考虑这样的想法:
AttributedString(localized: "^[\(amount) \(String(unit.dropLast()))](inflect: true)")
本质上,我们只是从
unit
中删除了最后一个角色,但这显然并不像系统自行处理一样坚固。
我不会与扫地机竞争,但至少它比放下最后一封信要好一点:
NLTagger
如果需要,您还可以包括不规则的复数名词:
private func singular(_ word: String) -> String {
if word.hasSuffix("ies") {
String(word.dropLast(3)) + "y"
} else if word.hasSuffix("ves") {
String(word.dropLast(3)) + "f"
} else if word.hasSuffix("oes") {
String(word.dropLast(2))
} else if word.hasSuffix("s") {
String(word.dropLast())
} else {
word
}
}