ios - 类型 'String.Index' 不符合协议(protocol) 'IntegerLiteralConvertible'

标签 ios xcode swift

使用 Beta 3 时一切正常,现在我收到一个奇怪的错误,而且我不知道如何修复它。针对类似问题尝试了所有解决方案。

这是我的代码:

if !name.isEmpty {
        var splitted: [String] = name.componentsSeparatedByString(" ")

        for curPart in splitted {
            if !curPart.isEmpty {
                acronym += curPart.substringToIndex(1) //Error
            }
        }
        if (acronym as NSString).length > 2 {
            acronym = acronym.substringToIndex(2) //Error
        }
    }

两条标记线都给了我同样的错误:

Type 'String.Index' does not conform protocol 'IntegerLiteralConvertible'

有人可以帮助我吗?还是 Beta 4 被窃听了? 谢谢!

最佳答案

在 beta 4 中,Swift 的 String.Index 处理再次发生变化——当需要 String.Index 时,您现在不能提供 Int。处理它的方法是使用 advance 方法创建您需要的 String.Index:

if !name.isEmpty {
    var splitted: [String] = name.componentsSeparatedByString(" ")

    for curPart in splitted {
        if !curPart.isEmpty {
            acronym += curPart.substringToIndex(advance(curPart.startIndex, 1))
        }
    }
    if countElements(acronym) > 2 {
        acronym = acronym.substringToIndex(advance(acronym.startIndex, 2))
    }
}

这一切都是基于确保正确处理 Unicode 字符串 - 因为不同的 Unicode 字符可以有不同的大小,纯整数索引会隐藏字符串不是随机访问的事实。

关于ios - 类型 'String.Index' 不符合协议(protocol) 'IntegerLiteralConvertible',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880604/

相关文章:

iphone - 从核心数据获取请求中排除反向关系

iphone - 使用推送通知在指定页面打开应用程序

ios - 从后台线程更新 UIProgressView 进度

swift - 无效的 Swift 支持 xcode 8 itunesconnect 问题

swift - Xcode+Swift+XPC : How to start and deploy a Swift XPC target on MacOS

ios - Swift 的 TwitterKit 不显示图像

ios - AVPlayer 缓冲后未恢复

ios - 验证错误 : Invalid Bundle. ... 中的包包含不允许的文件 'Frameworks'

ios - 登录后使用 Swift 更改 ios 中的 MainViewController

ios - 在 iOS 应用程序中运行 R