gpt4 book ai didi

xcode - Swift 2 中的字符串索引

转载 作者:搜寻专家 更新时间:2023-10-30 22:35:36 24 4
gpt4 key购买 nike

我决定学习 Swift,并决定立即开始使用 Swift 2。

所以这是一个非常基本的示例,类似于 Apple 自己的关于 Swift 的电子书中的示例之一

let greeting = "Guten Tag"

for index in indices(greeting) {
print(greeting[index])
}

我在 Xcode 7 的 playground 上试过了,我收到了以下错误

Cannot invoke 'indices' with an argument list of type '(String)'

我也用 Xcode 6(据我所知是 Swift 1.2)尝试了同样的事情,它按预期工作。

现在,我的问题是:这是

  1. Xcode 7 中的错误,毕竟它仍然是测试版,或者
  2. 有些东西在 Swift 2 中不再适用,而且电子书还没有完全更新?

此外:如果答案是“2”,您将如何替换 Swift 2 中的 indices(String)

最佳答案

在 Playground 中,如果您转到菜单 View > Debug Area > Show debug area,您可以在控制台中看到完整的错误:

/var/folders/2q/1tmskxd92m94__097w5kgxbr0000gn/T/./lldb/94138/playground29.swift:5:14: error: 'indices' is unavailable: access the 'indices' property on the collection for index in indices(greeting)

此外,String 不再符合 SequenceType,但您可以通过调用 characters 访问它们的元素。

所以 Swift 2 的解决方案是这样的:

let greeting = "Guten Tag"

for index in greeting.characters.indices {
print(greeting[index])
}

结果:

G
u
t
e
n

T
a
g

当然,我假设你的例子只是为了测试indices,否则你可以这样做:

for letter in greeting.characters {
print(letter)
}

关于xcode - Swift 2 中的字符串索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30778373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com