Stringify
一系列有用的字符串扩展。
需求
- iOS 10.0+
- Swift 5+
安装
CocoaPods
Stringify 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中:
pod 'Stringify', '~> 1.0'
Swift Package Manager
Swift Package Manager 是一款用于自动分发 Swift 代码的工具,并与 swift
编译器集成。
一旦您设置了 Swift 包,将 Stringify 添加为依赖项就像将其添加到 Package.swift
中的 dependencies
值一样简单。
dependencies: [
.package(url: "https://github.com/NovichenkoAnton/Stringify.git", .upToNextMajor(from: "1.0.0"))
]
使用方法
字符串
- 在特定范围内为字符串应用掩码。该范围与
CountableRange
、ClosedRange
、PartialRangeFrom
、PartialRangeThrough
、PartialRangeUpTo
兼容。
let cardNumber = "1234567890123456"
let masked = cardNumber.maskSubstring(in: 6...13, with: "*")
print(masked!) //"123456********56"
- 将
String
转换为Double
。如果String
与Double
不兼容,则函数返回 0.00。
let amount = "100,12"
print(amount.toDouble()) //100.12
let anotherAmount = "1 200,10"
print(anotherAmount.toDouble()) //1200.1
- 可以为字符串应用特定格式
let sum = "1234"
let formattedSum = sum.st.applyFormat(.sum)
print(formattedSum) //"1 234,00"
支持的格式
enum Format {
case sum(minFractionDigits: Int = 2, maxFractionDigits: Int = 2)
case creditCard
case iban
case custom(formatter: NumberFormatter)
}
-
使用 Luhn 算法验证信用卡号。
-
使用特定模式验证字符串
"https://www.google.com".validate(with: .website) //true
- 简单日期格式化器(从一种格式转换为另一种格式)
let dateTime = "2019-11-22 13:33"
let resultTime = dateTime.st.convertDate(from: "yyyy-MM-dd HH:mm", to: "h:mm") //"1:33"
- 从
String
中获取与URL
类型对应的查询项。适用于包含西里尔字母域名的网址。
let stringURL = "https://test.com?foo=1&bar=abc"
let queryItems = stringURL.queryItems()! //["foo": "1", "bar": "abc"]
NSMutableAttributedString
- 您可以使用
+
追加两个属性字符串
let part1 = "123"
let part2 = "456"
myLabel.attributedText = part1.attributed + part2.attributed
- 为可变字符串应用属性
let string = "Some text"
label.attributedText = string.attributed.applyAttributes([
.color(color: .red),
.font(font: .systemFont(ofSize: 32, weight: .bold)),
.crossed(width: 1, color: .black),
.underline(style: .single, color: .blue)
])
- 为字符串应用样式
let sum = "1000,22"
label.attributedText = sum.attributed.applyStyle(.sum(integerAttrs: [
.color(color: UIColor.red),
.font(font: UIFont.systemFont(ofSize: 32, weight: .bold)),
.underline(style: .double, color: .black)
], fractionAttrs: [
.color(color: UIColor.green),
.font(font: UIFont.systemFont(ofSize: 24, weight: .medium)),
], currencyMark: "$"))