-3

I have a variable of type String in Swift, its content may be as follows:

var str:String = "45.7" //content is of float type

Or the contents may be:

var str:String = "45" //content is of int type

the content may also be of any other type having more numbers and/or decimals. How could I convert the String accordingly?

The variable is only one, there aren't two variables. And the value of the variable is not fixed, if it contains a decimal or not, it may contain a decimal point number or may not. The single variable may have the above possibilities of data stored.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Possible duplicate of [Swift - Converting String to Int](http://stackoverflow.com/questions/24115141/swift-converting-string-to-int) – FelixSFD Dec 17 '16 at 08:27

3 Answers3

1

You can use if let for that.

var str:String = "45.7" //content is of float type
if let _ = str.range(of: "."), let floatValue = Float(str)  {        
    //Execute if string contains float value
    print(floatValue)
}
else if let intValue = Int(str) {
    //Execute if string contains integer value
    print(intValue)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • If the string is "45", the conversion to `Float` still succeeds, although it would be an integer – FelixSFD Dec 17 '16 at 08:48
  • @FelixSFD Also check the edited answer with more detail, because if string contains multiple `.` it will crash, now it will not. – Nirav D Dec 17 '16 at 09:02
0

Via:

Float(str)

and:

Int(str)

respectively.

Or, if you don't know the numeric type at compile-time:

NumberFormatter().number(from: str)
Vatsal Manot
  • 17,695
  • 9
  • 44
  • 80
  • it is not fixed whether the value of the variable contains decimal or not. and the variable is single, The value of the variable changes according to user input. the second variable i put in the question is just to show the possibilities the String can contain. – Mohit Mishra Dec 17 '16 at 08:38
  • @MohitMishra: What you want is `NSNumber`. – Vatsal Manot Dec 17 '16 at 08:45
  • I just want to convert the string accordingly. And the contents of the string are not predetermined, it depends on user's input. If the user inputs a decimal point number, then i want to change it to a float type, And if the user simply enters a non-decimal point number, then i want to change it into Int type. – Mohit Mishra Dec 17 '16 at 08:48
0

In your playground:

func isContainPoint(_ string:String) -> Bool {

    if string.contains(".") {

        return true
    }else {

        return false
    }
}

var str1:String = "45.7" //content is of float type

var str2:String = "45" //content is of int type



if isContainPoint(str1) {

    print("\(Float(str1)!)")
}else {
    print("\(Int(str1)!)")
}

if isContainPoint(str2) {

    print("\(Float(str2)!)")
}else {
    print("\(Int(str2)!)")
}

Result is:

45.7
45
aircraft
  • 25,146
  • 28
  • 91
  • 166