Swift 3 从 Int 到 String 的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40198220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:34:28  来源:igfitidea点击:

Swift 3 conversion from Int to String

stringswift3

提问by Don Giovanni

In Swift 3, the Stringstructure does not seem to have an initializer init(_: Int)that will allow the conversion from an Intto a String. My question is why does let i = String(3)work? What Stringmethod or initializer is it calling? Thanks.

在 Swift 3 中,该String结构似乎没有init(_: Int)允许从 an 转换Int为 a的初始化程序String。我的问题是为什么let i = String(3)有效?String它调用什么方法或初始化程序?谢谢。

采纳答案by Alexander - Reinstate Monica

It's calling init(_:)(or init(_:)for UnsignedInteger) arguments of the Stringclass.

它正在调用init(_:)(或init(_:)for UnsignedIntegerString类的参数。

Rather than defining separate initializers for Int, Int64, Int32, Int16, Int8, UInt, UInt64, UInt32, UInt16, and UInt8, Apple made two generic initializers: one for SignedIntegertypes, and one for UnsignedIntegertypes.

Apple 没有为Int, Int64, Int32, Int16, Int8, UInt, UInt64, UInt32, UInt16, and定义单独的初始值设定项,而是UInt8制作了两个通用初始值设定项:一个用于SignedInteger类型,另一个用于UnsignedInteger类型。

回答by Chuck Smith

For anyone just looking to convert an int to string in Swift 3:

对于任何只想在 Swift 3 中将 int 转换为字符串的人:

let text = "\(myInt)"

回答by Satheeshwaran

For people who want to convert optional Integers to Strings on Swift 3,

对于想要在 Swift 3 上将可选整数转换为字符串的人,

String(describing:YourInteger ?? 0)

回答by Mercedes

I saw this solution to somebody, thank you, to that person, I don't remember who.

我在某人那里看到了这个解决方案,谢谢你,对于那个人,我不记得是谁。

infix operator ???: NilCoalescingPrecedence

public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
    switch optional {
    case let value?: return String(describing: value)
    case nil: return defaultValue()
    }
}

For example:

例如:

let text = "\(yourInteger ??? "0")"