0

我想遍历数组 String?,String 重复对,但我无法正确形成“for case let (a,b) in array”。

我想出的最好的方法是创建一个 {String?, String} 的临时结构并创建一个临时结构的数组,然后对其进行迭代,但我想跳过这一步。

下面是最后一个 for 循环显示错误 Xcode 报告的基本示例。

class Foo {
    var s1: String?
    var s2: String?
    var s3: String?
}

let foo = Foo()
foo.s1="Test1"
foo.s2=nil
foo.s3="Test3"

let fooArray = [foo.s1, ", ", foo.s2, "; ", foo.s3,"."]
let fooArray1 = [foo.s1,foo.s2, foo.s3]
var text:String = ""
for case let prop? in fooArray1 {
    text = text + prop + " / "
}
print(text)
// The above works but now I want to use a different separator 
//base on the property name

text=""

for case let (prop, sep) in fooArray { // Error <= Expression Type 
// [String?] is ambiguous without more context

    text = text + prop + sep
}
print(text)

这是我想出的

struct temp {
    var prop:String?
    var sep:String
    init(_ prop:String?, _ sep:String) {
        self.prop=prop
        self.sep=sep
}

let ary:[temp] = [ temp(foo.s1,", "), temp(foo.s2,"; "), temp(foo.s3,".") ]
text = ""
for a in ary {
    if let p = a.prop {
        text = text + p + a.sep
    }
}
print (text)

是否有另一种方法只是使用 for 循环

for (a,b) in fooArray {
...
}
4

2 回答 2

0

感谢您的回答,我希望通过这个问题能够更好地了解如何使用 [for] 参数。但是 while 解决方案是我可能会使用以下修改的解决方案

text = ""
var index = 0 
while index < fooArray.count {    
    if let prop = fooArray[index] {
        index += 1
        let sep = fooArray[index]!
        index += 1
        text = text + prop + sep
    } else {
        index += 2
    }
}
于 2019-04-27T13:53:45.400 回答
0

正如@RJE 所指出的,fooArray您的代码中定义的推断类型是[String?].

这是使其工作的一种方法:

class Foo {
    var s1: String?
    var s2: String?
    var s3: String?
}

let foo = Foo()
foo.s1 = "Test1"
foo.s2 = nil
foo.s3 = "Test3"

let fooArray1  = [foo.s1, foo.s2, foo.s3]
let separators = [", ", "; ", "."]

var text = ""

for i in fooArray1.indices {
    if let p = fooArray1[i] {
        text = text + p + separators[i]
    }
}

print (text)  //Test1, Test3.

或者

let zipped = zip(fooArray1, separators)

let text = zipped.map { tuple -> String in
    if case let (x?, y) = tuple {
        return x + y
    } else {
        return ""
    }
}.joined()

print (text)  //Test1,Test3.

或者

let fooArray = [foo.s1, ", ", foo.s2, "; ", foo.s3, "."]
var text = ""
var step = 1
var index = 0

while index < fooArray.count {
    if let str = fooArray[index] {
        step = 1
        text += str
    } else {
        step = 2
    }
    index += step
}

print(text) //Test1, Test3.

以这种方式定义初始化程序会更好:

class Foo {
    var s1: String?
    var s2: String?
    var s3: String?

    init(s1: String?, s2: String?, s3: String?) {
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
    }
}

let foo = Foo(s1: "Test1", s2: nil, s3: "Test3")

PS:所需的输出似乎更适合类的description属性Foo

于 2019-04-27T04:02:49.863 回答