Convert String to CGFloat in Swift

后端 未结 12 1193
长情又很酷
长情又很酷 2021-02-03 17:05

I\'m new to Swift, how can I convert a String to CGFloat?

I tried:

var fl: CGFloat = str as CGFloat
var fl: CGFloat = (CGFloat)str
var fl: CGFloat = CGFl         


        
12条回答
  •  深忆病人
    2021-02-03 17:21

    If you want a safe way to do this, here is a possibility:

    let str = "32.4"
    if let n = NSNumberFormatter().numberFromString(str) {
        let f = CGFloat(n)
    }
    

    If you change str to "bob", it won't get converted to a float, while most of the other answers will get turned into 0.0.

    For Swift 3.0, I'd do something like this:

    let str = "32.4"
    guard let n = NSNumberFormatter().number(from: str) else { return }
    // Use `n` here
    

    In Swift 4, NSNumberFormatter has been renamed to NumberFormatter:

    let str = "32.4"
    guard let n = NumberFormatter().number(from: str) else { return }
    

提交回复
热议问题