我是Swift的新手。我一直在做Java编程。我有一个场景可以在Swift中进行编码。
以下代码是Java语言。在以下情况下,我需要在Swift中进行编码
// With String array - strArr1 String strArr1[] = {"Some1","Some2"}
String strArr2[] = {"Somethingelse1","Somethingelse2"}
for( int i=0;i< strArr1.length;i++){ System.out.println(strArr1[i] + " - "+ strArr2[i]); } 我很快有几个数组
var strArr1: [String] = ["Some1","Some2"] var strArr2: [String] = ["Somethingelse1","Somethingelse2"]
for data in strArr1{ println(data) }
for data in strArr2{ println(data) } // I need to loop over in single for loop based on index. 您能否提供有关基于索引的循环语法的帮助? 问题来源于stack overflow
使用Swift 5,您可以使用以下4种Playground代码之一来解决您的问题。
#1 使用zip(::)功能 在最简单的情况下,您可以zip(::)用来创建初始数组中元素对的新序列(元组)。
let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]
let sequence = zip(strArr1, strArr2)
for (el1, el2) in sequence { print("(el1) - (el2)") }
/* prints: Some1 - Somethingelse1 Some2 - Somethingelse2 */ #2。使用Array的makeIterator()方法和while循环 使用简单的while循环和迭代器同时循环两个数组也很容易:
let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]
var iter1 = strArr1.makeIterator() var iter2 = strArr2.makeIterator()
while let el1 = iter1.next(), let el2 = iter2.next() { print("(el1) - (el2)") }
/* prints: Some1 - Somethingelse1 Some2 - Somethingelse2 */ #3。使用符合以下条件的自定义类型IteratorProtocol 在某些情况下,您可能需要创建自己的类型,以将姓名缩写数组的元素配对。可以通过使您的类型符合来实现IteratorProtocol。请注意,通过使您的类型也符合Sequence协议,您可以在for循环中直接使用其实例:
struct TupleIterator: Sequence, IteratorProtocol {
private var firstIterator: IndexingIterator<[String]>
private var secondIterator: IndexingIterator<[String]>
init(firstArray: [String], secondArray: [String]) {
self.firstIterator = firstArray.makeIterator()
self.secondIterator = secondArray.makeIterator()
}
mutating func next() -> (String, String)? {
guard let el1 = firstIterator.next(), let el2 = secondIterator.next() else { return nil }
return (el1, el2)
}
}
let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]
let tupleSequence = TupleIterator(firstArray: strArr1, secondArray: strArr2)
for (el1, el2) in tupleSequence { print("(el1) - (el2)") }
/* prints: Some1 - Somethingelse1 Some2 - Somethingelse2 */ #4。使用AnyIterator 作为上一个示例的替代方法,您可以使用AnyIterator。以下代码显示了在Array扩展方法中可能的实现:
extension Array {
func pairWithElements(of array: Array) -> AnyIterator<(Element, Element)> {
var iter1 = self.makeIterator()
var iter2 = array.makeIterator()
return AnyIterator({
guard let el1 = iter1.next(), let el2 = iter2.next() else { return nil }
return (el1, el2)
})
}
}
let strArr1 = ["Some1", "Some2", "Some3"] let strArr2 = ["Somethingelse1", "Somethingelse2"]
let iterator = strArr1.pairWithElements(of: strArr2)
for (el1, el2) in iterator { print("(el1) - (el2)") }
/* prints: Some1 - Somethingelse1 Some2 - Somethingelse2 */
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。