Swift: a pair of fun String initializers

Repeat

Initialize a string with repeated characters

for n in 1...5 {
    print("\(n): ", appendNewline: false)
    print(String(count: n, repeatedValue: 
        Character("*")))
}
print("")

This produces:

1: *
2: **
3: ***
4: ****
5: *****

Radix

Initialize a string by converting an integer with a specific base system.

extension Int {
    var binaryString : String {
        return String(self, radix:2)}
    var octalString : String {
        return String(self, radix:8)}
    var hexString : String {
        return String(self, radix:16)}
}

For example

23.binaryString // "10111"
23.octalString // "27"
23.hexString // 17

Comments are closed.