Bronze and Silver Challenge Solutions


#1

Hello, I came up with this:

import Cocoa

let start = playground.startIndex
let end = playground.index(start, offsetBy: 4)
let range = start...end
let firstFive = playground[range]

// Bronze Challenge

let empty = ""

if empty.startIndex == empty.endIndex {
    print("This string is empty.")
} // only when string is empty both startIndex en endIndex properties are equal (0)

if empty.isEmpty {
    print("This string is empty.")
} // cleaner way with the isEmpty property

// Silver Challenge

var unicodeScalarsString = ""
for scalar in firstFive.unicodeScalars {
    var unicode = String(format: "%04X", scalar.value)
    unicodeScalarsString += "\\u{\(unicode)}"
}
print (unicodeScalarsString)

Cheers,
Raf


#2

This line of code really interests me. How would I go about reading Apple’s documentation on it? I think I found it in "Xcode > Help > Documentation and API Reference" under "Foundation > String > init(format:_:)" but it doesn’t explain the semantics of the format: string.

Thanks for any pointers!

–Don


#3

The current API documentation for Swift is pretty disappointing: not even a decent table of contents let alone an explanation for “the semantics of the format: string.”

Have a look at String Format Specifiers in String Programming Guide.


#4

This is what I came up with for the challenges:

// Bronze

var str = “”

if str.startIndex == str.endIndex
{
print(“string is empty”)
}

if str.isEmpty
{
print(“string is empty”)
}

// Silver

let hello = "\u{0048}\u{0065}\u{006C}\u{006C}\u{006F}"
print(hello) // Hello

for char in hello.unicodeScalars
{
print("(char.value)") // 72 101 108 108 111
}

// modifying Raf’s code a little

let range = hello.startIndex…hello.endIndex
let firstFive = hello[range]

var unicodeScalarsString = ""
for scalar in firstFive.unicodeScalars {
var unicode = String(format: “%04X”, scalar.value)
unicodeScalarsString += “\u{(unicode)}”
}
print (unicodeScalarsString) // \u{0048}\u{0065}\u{006C}\u{006C}\u{006F}

Mitch


#5

For the silver challenge, I took the “replace” to mean that we should actually be replacing the characters within the original string, and did the following:

var playground = “Hello, playground"
let start = playground.startIndex
let end = playground.index(start, offsetBy: 4)
playground.replaceSubrange(start…end, with:”\u{0048}\u{0065}\u{006C}\u{006C}\u{006F}")


#6

To use the code

… = String(format: _, _)

should

import UIKit


#7

let emptry = “”;
print("(emptry.characters.count)");