gpt4 book ai didi

xcode - Swift String 有索引类型吗?

转载 作者:可可西里 更新时间:2023-11-01 01:36:28 24 4
gpt4 key购买 nike

据我所知,我了解到 Swift 字符串不能按整数值索引。但我很好奇索引的类型是什么,或者有没有。我在 Xcode palyground 中写了以下代码:

let greeting = "Hello! Tom"
let index = greeting.startIndex

通过点击键并点击索引值,Xcode推断索引类型为Index(请见下图)。但是,当我将第二行更改为

 let index: Index = greeting.startIndex

我从 Xcode 收到了两个错误警告

 error: use of undeclared type 'Index'
error: could not infer type for 'index'

Xcode不是告诉我它推断索引类型是Index吗,为什么我明确声明类型时会出现错误?谁能给我解释一下?

Xcode type infer

最佳答案

字符串类型有一个索引:

extension String {
public typealias Index = String.CharacterView.Index
/// The position of the first `Character` in `self.characters` if
/// `self` is non-empty; identical to `endIndex` otherwise.
public var startIndex: Index { get }
/// The "past the end" position in `self.characters`.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Index { get }
/// Access the `Character` at `position`.
///
/// - Requires: `position` is a valid position in `self.characters`
/// and `position != endIndex`.
public subscript (i: Index) -> Character { get }
}

声明 Index 在当前上下文中是不明确的。使用 String.Index 显式引用 String 扩展中定义的类型别名:

let index: String.Index = greeting.startIndex // 0

如果你真的想发疯,你可以在顶级范围内创建另一个类型别名:

public typealias Index = String.Index
let index: Index = greeting.startIndex // 0

虽然不确定我会推荐这个。

关于xcode - Swift String 有索引类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990630/

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