Swift 使用swit for loop解决编码BAT字符串_位问题

Swift 使用swit for loop解决编码BAT字符串_位问题,swift,loops,Swift,Loops,现在我的问题是: 我是否可以像object-c、c或其他编程语言那样,以任何方式在swift中迭代索引。例如: Question: Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". string_bits('Hello') → 'Hlo' string_bits('Hi')

现在我的问题是: 我是否可以像object-c、c或其他编程语言那样,以任何方式在swift中迭代索引。例如:

Question:
 
 Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".

 string_bits('Hello') → 'Hlo'
 string_bits('Hi') → 'H'
 string_bits('Heeololeo') → 'Hello'
 
Solution:

func string_bits(userString: String) ->String{
    var myString = ""
    
    
    for(i, v) in userString.enumerated(){
        if i % 2 == 0{
            myString.append(v)
        }
    }
    return myString
}

Output: Hello
str[:i+1] 在这里,我将+1与当前索引相加,得到索引值。我怎样才能在斯威夫特做到这一点

result = ""
  # On each iteration, add the substring of the chars 0..i
  for i in range(len(str)):
    result = result + str[:i+1] 
  return result

使用while循环的常规方法:

let alphabet = "abcdefghijklmnopqrstuvwxyz"
for evenIndex in alphabet.everyNthIndex(n: 2) {
    print("evenIndex", evenIndex, "char:", alphabet[evenIndex])
}
for oddIndex in alphabet.dropFirst().everyNthIndex(n: 2) {
    print("oddIndex", oddIndex, "char:", alphabet[oddIndex])
}

使用while循环的常规方法:

let alphabet = "abcdefghijklmnopqrstuvwxyz"
for evenIndex in alphabet.everyNthIndex(n: 2) {
    print("evenIndex", evenIndex, "char:", alphabet[evenIndex])
}
for oddIndex in alphabet.dropFirst().everyNthIndex(n: 2) {
    print("oddIndex", oddIndex, "char:", alphabet[oddIndex])
}

你的意思是使用
stride()
,这将允许你对(i=0;i有一个
(例如),然后如果需要,你可以使用
i+1
。@Larme我的朋友,谢谢你的快速回复。我没有。让我检查一下。但是如何传递那个索引号并得到那个索引值呢?请您添加示例?可能重复@FerrakkemBhuiyan您需要收藏的其他索引还是元素?您是否打算使用
stride()
,这将允许您为(i=0;i
(例如),如果需要的话,你可以使用
i+1
。@Larme我的朋友谢谢你的快速回复。我没有。让我检查一下。但是如何传递那个索引号并得到那个索引值呢?请您添加示例?可能是@FerrakkemBhuiyan的副本?您需要收藏的其他索引还是元素?谢谢您的时间。这意味着没有任何方法可以像objective-c、python和其他编程语言那样。正如我所说的,字符串不是由整数索引的,但您可以将其偏移,如上图所示
yourString.index(index,offsetBy:n)
感谢您的时间。这意味着没有像objective-c、python和其他编程语言那样的方法。正如我所说,字符串不是由整数索引的,但您可以按上面所示对其进行偏移。
yourString.index(index,offsetBy:n)
var index = alphabet.startIndex
while index < alphabet.endIndex {
    defer { index = alphabet.index(index, offsetBy: 1) }
    print(alphabet[index])
    print(index)
}
func string_bits(userString: String) -> String {
    var myString = ""
    for (offset,index) in userString.indices.enumerated() {
        if offset.isMultiple(of: 2) {
            myString.append(userString[index])
        }
    }
    return myString
}