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
Swift 3 conversion from Int to String
提问by Don Giovanni
In Swift 3, the String
structure does not seem to have an initializer init(_: Int)
that will allow the conversion from an Int
to a String
. My question is why does let i = String(3)
work? What String
method 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 String
class.
它正在调用init(_:)
(或init(_:)
for UnsignedInteger
)String
类的参数。
Rather than defining separate initializers for Int
, Int64
, Int32
, Int16
, Int8
, UInt
, UInt64
, UInt32
, UInt16
, and UInt8
, Apple made two generic initializers: one for SignedInteger
types, and one for UnsignedInteger
types.
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")"