'characters is unavailable' please use string directly

Viewed 1570

I can't figure out how to fix it. I just want to understand how it works and what should be replaced.

I've already tried to delete characters., but it still doesn't work.

import Foundation
var shrinking = String("hello")
repeat {
    print(shrinking)
    shrinking = String(shrinking.characters.dropLast())
}
while shrinking.characters.count > 0

I expected the program to output:

hello
hell
hel
he
h

but it doesn't work at all.

1 Answers

Your code should work as it is if you delete the characters I suggest you create a new playground file. Btw you can simply use RangeReplaceableCollection mutating method popLast and iterate while your string is not empty to avoid calling your collection count property multiple times:

var shrinking = "hello"
repeat {
    print(shrinking)
    shrinking.popLast()
} while !shrinking.isEmpty

This will print

hello

hell

hel

he

h

or using removeLast method but it requires the string not to be empty so you would need to check if the string is empty at before the closure:


var shrinking = "hello"

while !shrinking.isEmpty {
    print(shrinking)
    shrinking.removeLast()
}
Related