var someString ="Some String",var someString:String ="Some String",var someString ="Some String"作为字符串之间的区别
任何人都可以请我解释一下差异
Can anyone please explain me the difference
var someString = "Some String"
var someString: String = "Some String"
var someString = "Some String" as String
var someString = "Some String" as! String
var someString = "Some String" as? String
let someString = "Some String"
let someString: String = "Some String"
对于这两个:
两者之间的运行时效率差异为零.在编译期间,Swift会推断类型并为您编写.但是一旦编译,这两个语句是相同的.
There’s zero runtime efficiency difference between the two. During compilation, Swift is inferring the type and writing it in for you. But once compiled, the two statements are identical.
let someString = "Some String" as String
意味着您要将 someString
值转换为字符串(如果不是字符串).
Means you are casting someString
value to string if it is not string.
let someString = "Some String" as! String
意味着您将"Some String"强制转换为字符串,但是如果它不能转换为字符串,则会使应用程序崩溃.
Means you are forcibly casting "Some String" as a string but if it is not convertible to string then it will crash the app.
let someString = "Some String" as? String
意味着您可以选择将某些字符串"
强制转换为字符串,这意味着如果它不能转换为字符串,则它将返回nil但此时不会崩溃.
Means you are optionally casting "Some String"
to string means if it is not convertible to string then it will return nil but wont crash at this point.
对于最后3条语句它可以编译并工作,但是将String强制转换为String绝对是错误的.无需将 String
强制转换为 String
.
For last 3 Statement It would compile and work but it is definitely wrong to cast String to String. there is no need to cast a String
to String
.
最后2个 as?
和 as!
在您的情况下总是可以成功的.
And the the last 2 as?
and as!
would always succeed in your case.
请考虑以下示例:
let stringObject: AnyObject = "Some String"
let someString3 = stringObject as! String
let someString5 = stringObject as? String
这是您需要投射的时间.仅当您知道它是字符串时,才使用 as!
.如果您不知道它是否为字符串,请使用 as?
.
This is when you will need to cast. Use as!
only if you know it is a string. And use as?
if you doesn't know that it will be string or not.
仅在确定使用其他条件转换时,才用 as!
强制向下转换:
only force downcast with as!
if you are sure otherwise use conditional cast like this:
if let someString5 = stringObject as? String {
println(someString5)
}