“字符不可用”,请直接使用字符串 [英] 'characters is unavailable' please use string directly

查看:104
本文介绍了“字符不可用”,请直接使用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何解决它。我只想了解它的工作原理以及应该替换的内容。

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

我希望程序输出:

你好

地狱

hel

he

h

hello
hell
hel
he
h

,但根本不起作用。

推荐答案

您的代码如果删除字符应该可以正常工作,建议您创建一个新的Playground文件。顺便说一句,您可以简单地使用 RangeReplaceableCollection 变异方法 popLast 并在字符串不为空时进行迭代,以避免调用集合计数属性多次:

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

这将打印


你好

hello

地狱

hel

he

h

或使用 removeLast 方法,但它要求字符串不为空,因此您需要在关闭前检查字符串是否为空:

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

这篇关于“字符不可用”,请直接使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆