swift如何从Int转换?到String

时间:2015-02-03 03:23:40

标签: swift

在Swift中,我无法通过以下方式将Int转换为String:

var iString:Int = 100
var strString = String(iString)

但我在Int中的变量? ,出错:Cant invoke 'init' with type '@Ivalue Int?'

实施例

let myString : String = "42"
let x : Int? = myString.toInt()

if (x != null) {
    // Successfully converted String to Int
    //And how do can i convert x to string???
}

11 个答案:

答案 0 :(得分:38)

您可以使用字符串插值。

let x = 100
let str = "\(x)"

如果x是可选的,您可以使用optional binding

var str = ""
if let v = x {
   str = "\(v)"
}
println(str)

如果您确定x永远不会nil,则可以forced unwrapping optional value进行var str = "\(x!)"

let str = x != nil ? "\(x!)" : ""

在单个声明中,您可以尝试这个

nil coalescing operator (??)

根据@ RealMae的评论,您可以使用let str = x ?? ""

进一步缩短此代码
{{1}}

答案 1 :(得分:19)

我喜欢为此创建小扩展程序:

extension Int {
    var stringValue:String {
        return "\(self)"
    }
}

这使得调用可选的int成为可能,而不必打开并考虑nil值:

var string = optionalInt?.stringValue

答案 2 :(得分:9)

If you need a one-liner it can be achieved by:

let x: Int? = 10
x.flatMap { String($0) } // produces "10"
let y: Int? = nil
y.flatMap { String($0) } // produces nil

if you need a default value, you can simply go with

(y.flatMap { String($0) }) ?? ""

EDIT:

Even better without curly brackets:

y.flatMap(String.init)

Apple's flatMap(_:) Documentation

答案 3 :(得分:3)

可选的Int - >可选字符串:

如果<h4>With image</h4> <div id="container"> <div class="main-image"> <img src="http://i2.cdn.turner.com/cnnnext/dam/assets/151009172735-02-tbt-bob-dylan-restricted-super-169.jpg"> </div> </div> <h4>With background-image</h4> <div id="container2"> <div class="main-image-bg"></div> </div>(或import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Test { private static ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(0); public static void onTimer() { System.out.println("onTimer"); while (true) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { } } } public static void onTimer2() { System.out.println("onTimer2"); } public static void main(String[] args) { threadPool.scheduleAtFixedRate(Test::onTimer, 0, 500, TimeUnit.MILLISECONDS); threadPool.scheduleAtFixedRate(Test::onTimer2, 0, 500, TimeUnit.MILLISECONDS); } } - 无关紧要)

x: Int?

这将返回Double?

要获得var s = x.map({String($0)}) ,您可以使用:

String?

答案 4 :(得分:1)

Sonrobby,我相信“Int?”表示可选的int。基本上,根据我的理解,需要打开包装。

所以做以下工作很好:

let y: Int? = 42
let c = String(y!)

那个“!”展开变量。希望这有帮助!

正如rakeshbs所提到的那样,确保变量不会是nill。

答案 5 :(得分:1)

你需要&#34;解开&#34;你的可选项是为了获得它内部的真正价值as described here。用&#34;!&#34;打开一个选项。因此,在您的示例中,代码将是:

let myString : String = "42"
let x : Int? = myString.toInt()

if (x != null) {
    // Successfully converted String to Int
    // Convert x (an optional) to string by unwrapping
    let myNewString = String(x!)
}

或者在该条件中,您可以使用字符串插值:

let myNewString = "\(x!)" // does the same thing as String(x!)

答案 6 :(得分:1)

为了防止不安全的可选unwraps,我按照@ AntiStrike12的建议使用它,

 if let theString = someVariableThatIsAnInt  {        
    theStringValue = String(theString!))
 }

答案 7 :(得分:0)

也许是粗暴,但你可以这样做:

let int100 = 100
println(int100.description) //Prints 100

答案 8 :(得分:0)

Swift 3:

ini_set('default_socket_timeout', 120);

这可以避免使用详细信息:var iString:Int = 100 var strString = String(iString) extension String { init(_ value:Int){/*Brings back String() casting which was removed in swift 3*/ self.init(describing:value) } }

乱丢代码

加分:为常用类型添加类似的初始化方法,例如:String(describing:iString)Bool等。

答案 9 :(得分:0)

您可以尝试转换Int吗?字符串

let myString : String = "42"
let x : Int? = myString.toInt()

let newString = "\(x ?? 0)"
print(newString)        // if x is nil then optional value will be "0"

答案 10 :(得分:0)

希望这会有所帮助

var a = 50
var str = String(describing: a)