swift - 字符串插值表达式中的文字

标签 swift

我可以在字符串插值表达式中写文字吗?怎么办?

“项目数:\(items > 0 ? items :"zero")"

最佳答案

documentation似乎暗示转义内插字符串中的文字在某种程度上是可能的

The expressions you write inside parentheses within an interpolated string cannot contain an unescaped double quote (") or backslash (), and cannot contain a carriage return or line feed.

但是,据我所知,目前没有办法。

可能的解决方法是字符串连接:

"Number of items: " + (items > 0 ? "\(items)" : "zero")

或者简单地使用一个变量

let nOfItems = items > 0 ? "\(items)" : "zero"
"Number of items: \(nOfItems)"

关于swift - 字符串插值表达式中的文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25997790/

相关文章:

ios - 入职/演练自动加载

Swift:泛型和类型约束,奇怪的行为

ios - 无法从 RLMResult 获取对象(Swift)

ios - Swift:如何以编程方式更改 View 的位置?

ios - 并非所有 Stripe 占位符同时在我的屏幕上可见

ios - SWIFT:执行 UIButton 操作时会删除解析数据

ios - 在自定义键盘内添加相机 View - Swift 3.0 和 IOS 10

swift - 在 Swift 中转换 followPath(_ :asOffset:orientToPath:speed:) to iOS 7. 1 兼容版本

ios - 如何使用 SLComposeViewController 检测用户成功分享到 Facebook

ios - UserDefaults 不会调用 UIPickerView didSelect Int