gpt4 book ai didi

ios - swift 中的 "as string"和 "stringvalue"有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:57 31 4
gpt4 key购买 nike

我有一个代码:

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

it get crashed on as String line but runs in second i.stringValue.

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

最佳答案

.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.

关于ios - swift 中的 "as string"和 "stringvalue"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32837053/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com