Convert Optional String to Int in Swift

Convert optional string to int in Swift

You can unwrap it this way:

if let yourStr = str_VAR?.toInt() {
println("str_VAR = \(yourStr)") //"str_VAR = 100"
println(yourStr) //"100"

}

Refer THIS for more info.

When to use “if let”?

if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. Let’s have a look:

if let yourStr = str_VAR?.toInt() {
println("str_VAR = \(yourStr)")
println(yourStr)

}else {
//show an alert for something else
}

The if let structure unwraps str_VAR?.toInt() (i.e. checks if there’s a value stored and takes that value) and stores its value in the yourStr constant. You can use yourStr inside the first branch of the if. Notice that inside the if you don’t need to use ? or ! anymore. It’s important to realise thatyourStr is actually of type Int that’s not an Optional type so you can use its value directly.

Converting Optional String to Int in Swift 4

You need

if let nScore = Int(pData.info?.myScore ?? "0" ) , nScore > 0 {

}

Simplest way to convert an optional String to an optional Int in Swift

You can use the nil coalescing operator ?? to unwrap the String? and use a default value "" that you know will produce nil:

return Int(value ?? "")

Another approach: Int initializer that takes String?

From the comments:

It's very odd to me that the initializer would not accept an optional and would just return nil if any nil were passed in.

You can create your own initializer for Int that does just that:

extension Int {
init?(_ value: String?) {
guard let value = value else { return nil }
self.init(value)
}
}

and now you can just do:

var value: String?
return Int(value)

Swift Converting Optional String to Int

Maybe, your String.init(describing:) is extraneous and unnecessary.

    if let xRate = response.response?.allHeaderFields["X-Ratelimit-Remaining"] as? String {
self.jsonCallsRemaining = xRate
print("json: ", xRate)
print("json2: ", Int(xRate))
}

Unwrapping Optional String To Int & Making it non-optional

If you are frequently getting value from UITextField as Int, you can add an extension as follows:

extension UITextField {
var intValue: Int {
get {
if let text = self.text {
return Int(text) ?? 0
}
return 0
}
set {
self.text = String(newValue)
}
}
}

You can add the above as private extension in your viewcontroller too. Now you can rewrite your code as:

func sendScore() {
let strData = "S|R\(txtRuns.intValue)\(overs.intValue)\(wkts.intValue)" + getOptionalScoreData(
runs: txtRuns.intValue,
wkts: wkts.intValue,
overs: overs.intValue,
balls: balls.intValue,
target: target.intValue,
totalOvers: totalOvers.intValue)
)
}

Convert Int to String in Swift and remove optional wrapping?

a is an Optional, so you need to unwrap it prior to applying a String by Int initializer to it. Also, b needn't really be an Optional in case you e.g. want to supply a default value for it for cases where a is nil.

let a: Int? = 1
let b = a.map(String.init) ?? "" // "" defaultvalue in case 'a' is nil

Or, in case the purpose is to assign the possibly existing and possibly String-convertable value of a onto the text property of an UILabel, you could assign a successful conversion to the label using optional binding:

let a: Int? = 1
if let newLabelText = a.map(String.init) {
self.label.text = newLabelText
}


Related Topics



Leave a reply



Submit