How to Convert Strings into Double, Float, and Int Numbers Using Swift 2 - Swift Tips 4

Опубликовано: 23 Октябрь 2015
на канале: Paul Solt
13,403
44

How to Convert Strings into Double, Float, and Int Numbers Using Swift 2 - Swift Tips 4

http://iPhoneDev.tv/SwiftTips

In Swift 2, you get native support for working with different numeric types (Float, Double, and Int) and Strings. Prior to Swift 2, you had to do a lot of extra work to convert between types.

Swift 2 allows you to quickly change a String into a number (if it’s a valid conversion).

To convert, you need to use a new style, which is Apple’s recommended best practice.

Use the initializer for the type instead of the toInt() style that was available in Swift 1.2 and earlier.

Use Int and variants like Int32, UInt64, etc. to convert integer values.

var wholeNumber = Int("27")


Use Float or Double to convert floating-point values (real numbers).

let lessPrecisePI = Float("3.14")
let morePrecisePI = Double("3.1415926536")


These conversions can fail, which is why the Int(), Float(), and Double() initializers return an optional type (i.e.: Double?, Float?, Int?, etc.). If the value cannot be converted, the value will be nil.

let invalidNumber = Float("alphabet") // nil, not a valid number


To use the numbers, you need to unwrap them – I recommend using the if let syntax for user input from a UITextField (or you can try the new guard statement in Swift 2!).

if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}


You will need to unwrap the optional to get the value. The if let syntax above makes it safe to use cost if it’s a valid number, otherwise you can handle the invalid case (i.e.: “alphabet” is not a valid number, so it would become nil).

The new initializers for different value types have made Swift feel more unified – the simple conversions between types are a lot easier and straightforward. User input and JSON data parsing is much easier in Swift 2.



Learn how to make your own iPhone apps using Swift 2, iOS 9, and Xcode 7.

Click here to Subscribe on YouTube: http://www.youtube.com/subscription_c...

iPhone app blog: http://iPhoneDev.tv/blog
Swift Courses: http://learn.iphonedev.tv/course/pro/
Super Easy iPhone Apps: https://www.kickstarter.com/projects/...


Смотрите видео How to Convert Strings into Double, Float, and Int Numbers Using Swift 2 - Swift Tips 4 онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Paul Solt 23 Октябрь 2015, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 13,403 раз и оно понравилось 44 людям.