下面是一段代码,它允许我在 UIAlertViewController 消息中显示两个字符串,但是 Alert 显示的字符串周围带有可选括号,除了下面的代码之外,任何人都可以帮助/知道更好的使用方法,提前致谢。
var show = [(String,String)]()
show.append(("our-Show", (OurUpdate?.theVersion)!))
show.append(("the-Show", (TheUpdate?.theVersion)!))
let alert = UIAlertController(title: "Updated", message:"\(show)", preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
let delay = 5.0 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: {
self.dismiss(animated: true, completion: { _ in })
})
最佳答案
问题是您正在使用字符串插值将元组数组转换为字符串。这就是添加方括号、引号和圆括号的内容。对原始类型和其他字符串以外的任何内容使用字符串插值绝不是一个好主意。
因此,第一步是将您的元组数组正确地转换为您实际需要的格式的字符串。
这是一种方法:
let showStr = show.map { "\($0.0): \($0.1)" }.joined(separator: ", ")
let alert = UIAlertController(title: "Updated", message: showStr, preferredStyle: UIAlertControllerStyle.alert)
这将给出输出:
our-Show: 1-5, the-Show: 1-6
这里使用 map
将元组数组转换为字符串数组,其中每个字符串组合元组中的两个字符串,并用冒号分隔它们。然后 joined
调用将新的字符串数组组合成一个最终字符串,每个字符串之间用逗号分隔。
当然,您可以将其更改为任何您希望的格式。
作为旁注,以下代码是危险的:
show.append(("the-Show", (TheUpdate?.theVersion)!))
如果 TheUpdate
为 nil
,此代码将崩溃。您确实需要避免强制展开,尤其是与可选链接结合使用时。更安全的方法是这样的:
show.append(("the-Show", TheUpdate?.theVersion ?? "Some Default"))
如果 TheUpdate
为 nil
,则应将 "Some Default"
替换为您要使用的任何值。
关于ios - 在 Swift 3.0 中将 [String, String] 添加到没有 Optional\"(Help)"的 UIAlertController 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656624/