2016-12-02 50 views
0

目前我正在試圖在操場上混淆這一點之前,我的實際代碼中實現了一些這樣的版本。我正在嘗試取一個字符串並打印出4個字符。下面顯示的代碼,我打算在一個循環中使用,並將開始和結束位置增加4,這就是爲什麼當前位於起點和終點的變量。之前,我甚至可以到達那裏但是,我得到一個錯誤:斯威夫特子串初始化

error: cannot invoke initializer for type 'Range' with an argument list of type '(start: String.CharacterView.Index, end: String.CharacterView.Index)'

var str_start = 0

var str_end = 4

let sub_str = initial_str.substring(Range<String.Index>(start: initial_str.startIndex.advancedBy(str_start), end: initial_str.endIndex.advancedBy(str_end))) 

我已經看過這些資料,但無濟於事:

Creating Range<String.Index> from constant Ints

Cannot invoke initializer for type 'Range<String.Index>' with an argument list of type '(start: String.Index, end: String.Index)'

任何援助非常感謝,我很抱歉,如果它是一個簡單的修復。

回答

1

下面是做這件事:

let initialString = "foo bar" 

let newStartIndex = initialString.index(initialString.startIndex, offsetBy: 1) 
let newEndIndex = initialString.index(initialString.endIndex, offsetBy: -1) 
let substring = initialString[newStartIndex..<newEndIndex] 

// this also works, but it needs `import Foundation`: 
// let substring = initialString.substring(with: newStartIndex..<newEndIndex) 

print(substring) 

輸出:

oo ba 
+2

swiftConventionIsToUseCamelCase不snake_case – Alexander

+0

完美,我可以使這項工作就像我想與原來的代碼。非常感謝你 – Anavas