League2eb

舉個例子

信用卡輸入後,UI有可能會是這樣顯示

1
0000-0000-0000-0000

假設這個應用的UI不是設定四個TextField
那這時,就有必要在指定的範圍內加入指定字串

extension

1
2
3
4
5
6
7
8
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func insert(separator: Self, every count: Int) {
for i in indices.reversed() where i != startIndex &&
distance(from: startIndex, to: i) % count == 0 {
insert(contentsOf: separator, at: i)
}
}
}

使用

1
2
3
4
var creditcard: String = "1111222233334444"
creditcard.insert(separator: "-", every: 4)
print(creditcard)
//1111-2222-3333-4444

 評論