Convert String to CGFloat in Swift

后端 未结 12 1160
长情又很酷
长情又很酷 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:23
    let myFloatNumber = CGFloat("4.22")
    
    0 讨论(0)
  • 2021-02-03 17:24

    This is kind of a work around, but you can cast it as an NSString, then get the float value, then initialize a CGFloat from that value. Example:

    let str = "1.02345332"
    let foo = CGFloat((str as NSString).floatValue)
    
    0 讨论(0)
  • 2021-02-03 17:26

    This works:

    let str = "3.141592654"
    let fl = CGFloat((str as NSString).floatValue)
    
    0 讨论(0)
  • 2021-02-03 17:29

    You can make an extension that adds an init to CGFloat

    extension CGFloat {
    
        init?(string: String) {
    
            guard let number = NumberFormatter().number(from: string) else {
                return nil
            }
    
            self.init(number.floatValue)
        }
    
    }
    

    Use it like so let x = CGFloat(xString)

    0 讨论(0)
  • 2021-02-03 17:32

    in Swift 3.1

    if let n = NumberFormatter().number(from: string) {
       let fl = CGFloat(n)
    } 
    

    or:

    let fl = CGFloat((str as NSString).floatValue))
    
    0 讨论(0)
  • 2021-02-03 17:39

    As of Swift 2.0, the Double type has a failable initializer that accepts a String. So the safest way to go from String to CGFloat is:

    let string = "1.23456"
    var cgFloat: CGFloat?
    
    if let doubleValue = Double(string) {
        cgFloat = CGFloat(doubleValue)
    }
    
    // cgFloat will be nil if string cannot be converted
    

    If you have to do this often, you can add an extension method to String:

    extension String {
    
      func CGFloatValue() -> CGFloat? {
        guard let doubleValue = Double(self) else {
          return nil
        }
    
        return CGFloat(doubleValue)
      }
    }
    

    Note that you should return a CGFloat? since the operation can fail.

    0 讨论(0)
提交回复
热议问题