![](/img/trans.png)
[英]What is the difference between [[String:String]]! and [[String:String]]() in Swift
[英]What is the difference between “ as string” and “stringvalue” in swift?
我有一个代码:
var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)
它
as String
行崩溃但在第二个i.stringValue
运行。
上面这些行中的String
和stringValue
什么区别?
.stringValue
是一种将Integer提取为字符串值的方法,但是as String
不适用.stringValue
而且如果你使用as String
那么Xcode会强制你添加!
as
它不好,它永远不会成功,它会崩溃你的应用程序。 你不能将Int
为String
。 它总是会失败。 这就是为什么当你这样做as! String
as! String
它崩溃了应用程序。
所以铸造在这里不是一个好主意。
以下是将Integer提取为字符串值的更多方法:
let i : Int = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
这里你不能使用let forthway = i.stringValue
因为Int没有名为stringValue
成员
但你可以用anyObject
做同样的事情,如下所示:
let i : AnyObject = 5 // 5
let firstWay = i.description // "5"
let anotherWay = "\(i)" // "5"
let thirdWay = String(i) // "5"
let forthway = i.stringValue // "5" // now this will work.
两者都将Int转换为String,但这将不再起作用。 在Swift 2中,不可能这样做。
你应该使用:
let i = 5
print(String(format: "%i", i))
这将特别将int值写为String
使用as String
,你不能转换值,但你定义该变量包含String
但在你的情况下它是Int
.so它崩溃。
而另一种方式,即i.stringValue
将您的值转换为String
。因此它不会给您任何崩溃并成功转换为String值。
注意:当您使用
AnyObject
,变量具有成员stringvalue
...但Int没有...要转换Int值检出@Dharmesh Kheni回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.