【问题标题】:What is the difference between " as string" and "stringvalue" in swift?swift中的“as string”和“stringvalue”有什么区别?
【发布时间】:2015-12-26 12:36:18
【问题描述】:

我有一个代码:

var i : AnyObject!
i = 10
println(i as String)
println(i.stringValue)

它在as String 行崩溃,但在第二行运行i.stringValue

以上几行中的StringstringValue有什么区别?

【问题讨论】:

    标签: ios string swift typecasting-operator


    【解决方案1】:

    .stringValue 是一种将 Integer 提取为字符串值的方法,但 as String 将不起作用如果您使用 as String 然后 Xcode 将强制您添加 !as 这不好它永远不会成功,它会使你的应用程序崩溃。你不能将Int 转换为String。它总是会失败。这就是为什么当您执行 as! String 时,应用程序会崩溃。

    所以在这里投射不是一个好主意。

    这里还有一些将整数提取为字符串值的方法:

    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.
    

    【讨论】:

      【解决方案2】:

      使用as String,您不能转换该值,但您定义该变量包含String,但在您的情况下它是Int。所以它崩溃了。

      而另一种方式,即i.stringValue 将您的值转换为String。所以它不会给您任何崩溃并成功转换为字符串值。

      注意:当您使用 AnyObject 时,变量有成员 stringvalue...但 Int 没有...要转换 Int 值,请查看 @Dharmesh Kheni 答案

      【讨论】:

        【解决方案3】:

        两者都将 Int 转换为 String,但这将不再起作用。 在 Swift 2 中,不可能那样做。

        你应该使用:

        let i = 5
        print(String(format: "%i", i))
        

        这将专门将 int 值写为字符串

        【讨论】:

          猜你喜欢
          • 2010-10-06
          • 1970-01-01
          • 2012-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-11
          • 2018-06-07
          • 2012-10-06
          相关资源
          最近更新 更多