在 Swift 中,当每对元素都是字符串时,如何遍历一个数组以获取 2 个变量?和一个字符串
Posted
技术标签:
【中文标题】在 Swift 中,当每对元素都是字符串时,如何遍历一个数组以获取 2 个变量?和一个字符串【英文标题】:In Swift How do I iterate over an array getting 2 variables when each pair of elements is a String? and a String 【发布时间】:2019-04-27 03:21:53 【问题描述】:我想遍历一个数组 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
...
【问题讨论】:
fooArray
不是 (String, String) 的数组。但是let fooArray = [(foo.s1, ", "), (foo.s2, "; "), (foo.s3,".")]
是一个 (String, String) 的数组
【参考方案1】:
正如@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")
P.S:所需的输出似乎更适合Foo
类的description
属性。
【讨论】:
【参考方案2】:感谢您的回答,我希望通过这个问题能够更好地了解如何使用 [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
【讨论】:
以上是关于在 Swift 中,当每对元素都是字符串时,如何遍历一个数组以获取 2 个变量?和一个字符串的主要内容,如果未能解决你的问题,请参考以下文章
用 Python 交换字符串中每对相邻字符的最简单方法是啥?