簡體   English   中英

Swift:切片startIndex始終為0

[英]Swift: Slice startIndex always 0

我與Swift Slice發生沖突,認為firstIndex應該是該片段在源域中的第一個索引(不確定它還有什么用)。 顯然情況並非如此:

let ary = map(1...100) { i in i }

let s:Slice<Int> = ary[10..<20]
s.startIndex            // 0
ary[10..<20].startIndex // 0

(10..<20).startIndex    // 10 (half-open interval generated from a range, presumably)

這看起來像個蟲子嗎? 如果始終為0,則似乎完全沒有用。

如果您瀏覽自動生成的Swift頭文件(目前大多數文檔都在其中),則會發現此內容描述了Slice

/// The `Array`-like type that represents a sub-sequence of any
/// `Array`, `ContiguousArray`, or other `Slice`.

由於SliceArray式的,它有一定意義上startIndex將返回0 ,因為一個ArraystartIndex總是將是0 再往下,它在定義startIndex ,您還將看到:

/// Always zero, which is the index of the first element when non-empty.
var startIndex: Int { get }

如果要在Slice查找第一個條目,只需使用: s.first

/// The first element, or `nil` if the array is empty
var first: T? { get }

如果您需要在Slice開始的原始Array中找到索引,則可以執行以下操作:

if let startValue = s.first {
    let index = find(ary, startValue)
    /* ... do something with index ... */
}

在Swift 2中已修復。如果對范圍為2...5的數組進行切片,切片的startIndex將為2。非常酷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM