'characters is unavailable' please use string directly

帅比萌擦擦* 提交于 2020-01-30 06:42:07

问题


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:


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()
}


来源:https://stackoverflow.com/questions/56813986/characters-is-unavailable-please-use-string-directly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!