繁体   English   中英

如何使用 Swift 更改或更新数组字符串

[英]How to change or update string of array with Swift

这是数组:

    var newArray = [

                    "self.Button.setTitle(\"𝑨\", for: .normal)", 
                    "self.Button.setTitle(\"𝑩\", for: .normal)", 
                    "self.Button.setTitle(\"𝑪\", for: .normal)", 
                    "self.Button.setTitle(\"𝑫\", for: .normal)"
                    ]

我想像这样更新或打印出来:

                    "self.aButton.setTitle("𝑨", for: .normal)"
                    "self.bButton.setTitle("𝑩", for: .normal)"
                    "self.cButton.setTitle("𝑪", for: .normal)"
                    "self.dButton.setTitle("𝑫", for: .normal)"

任何想法将不胜感激。

更新:我尝试的是:

var anotherArray = ["a", "b", "c", "d"]

for value in newArray {

    for anotherValue in anotherArray {
     print(i.replacingOccurrences(of: "Button", with: value))

  }
}

但它会打印出:

self.aButton.setTitle("𝑨", for: .normal)
self.bButton.setTitle("𝑨", for: .normal)
self.cButton.setTitle("𝑨", for: .normal)
self.dButton.setTitle("𝑨", for: .normal)
self.aButton.setTitle("𝑩", for: .normal)
self.bButton.setTitle("𝑩", for: .normal)
self.cButton.setTitle("𝑩", for: .normal)
self.dButton.setTitle("𝑩", for: .normal)
self.aButton.setTitle("𝑪", for: .normal)
self.bButton.setTitle("𝑪", for: .normal)
self.cButton.setTitle("𝑪", for: .normal)
self.dButton.setTitle("𝑪", for: .normal)
self.aButton.setTitle("𝑫", for: .normal)
self.bButton.setTitle("𝑫", for: .normal)
self.cButton.setTitle("𝑫", for: .normal)
self.dButton.setTitle("𝑫", for: .normal)

我想要的是:

                    "self.aButton.setTitle("𝑨", for: .normal)"
                    "self.bButton.setTitle("𝑩", for: .normal)"
                    "self.cButton.setTitle("𝑪", for: .normal)" 
                    "self.dButton.setTitle("𝑫", for: .normal)"

这就是我提出这个问题的原因,我知道它没有用,因为它的方向错误,所以我没有发布我尝试过的内容。

这是一种可能的方法:

var letters: [Character] = ["a", "b", "c", "d"]

let insertionIndex = newArray[0]
    .index(newArray[0].startIndex, offsetBy: 5)

for index in newArray.indices {
    newArray[index].insert(letters[index], at: insertionIndex)
}

你可以这样检查结果:

newArray.forEach { print($0) }

哪个打印:

  self.aButton.setTitle("𝑨", for: .normal)\n self.bButton.setTitle("𝑩", for: .normal)\n self.cButton.setTitle("𝑪", for: .normal)\n self.dButton.setTitle("𝑫", for: .normal)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM