Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'characters is unavailable' please use string directly

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.

like image 442
Анастасия Лермонтова Avatar asked Jan 22 '26 12:01

Анастасия Лермонтова


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()
}
like image 198
Leo Dabus Avatar answered Jan 24 '26 04:01

Leo Dabus