Removing "Optional" in Swift 4 [duplicate] - swift

This question already has answers here:
How do I prevent my text from displaying Optional() in the Swift interpolation?
(3 answers)
Closed 5 years ago.
That's my code
let temperature = String(describing: Int(incomeTemp.text!))
celcjuszScore.text = "\(temperature)"
print(temperature)
Whent I am pushing a button, the result of print is "Optional(32)" (When I am writing 32 in incomeTemp). I would like to have "Optional" removed and only "32" should stay.

Just unwrap it.
if let temperature = Int(incomeTemp.text!) {
celcjuszScore.text = "\(temperature)"
print(temperature)
}

Remove the optional when converting text to number: Int(incomeTemp.text!) ?? 0.
Or solve the error explicitly:
if let temperature = Int(incomeTemp.text ?? "") {
celcjuszScore.text = "\(temperature)"
} else {
celcjuszScore.text = "Invalid temperature"
}

Related

How can I remove character in specific range [duplicate]

This question already has an answer here:
Understanding the removeRange(_:) documentation
(1 answer)
Closed 2 years ago.
how can i remove character from string with rang. for example «banana» i want to remove only a from index (1..<3), i don’t want to remove the first and last character if they where «a»
i want from banana to bnna only removed the two midle.
the only thing i can do now is to remove the all “a”.
var charr = "a"
var somfruit = "banana"
var newString = ""
for i in somfruit{
if charr.contains(i) {
continue
}
newString.append(i)
}
print(newString)
In SWIFT 5 try:
var charr = "a"
var somfruit = "banana"
var newString = ""
let lower = somfruit.firstIndex(of: charr) + 1
let upper = somfruit.lastIndex(of: charr) - 1
newString = somfruit.replacingOccurrences(of: charr, with: '', option: nil, range: Range(lower, upper)
print(newString)
This is simplified. firstIndex and lastIndex returns Int? so you have to check they exist and they are not equals.

Convert entire string into integer and display it in textfield swift [duplicate]

This question already has answers here:
Converting String to Int with Swift
(31 answers)
Closed 3 years ago.
I want to develop an application that can convert UITextField values into integer, float and double.
I am facing problem to convert String value into Integer.
Can anyone suggest the better way for conversion.
I have tried the following code but it didn't worked for Swift 4 and Xcode 10.
let result = txtTotakeInput.text
var newSTrings = Int(result!)
Thanks in advance.
A better and safer way to handle all three types Int, Float and Double will be
let result = txtTotakeInput.text
if let intVal = Int(result ?? "") {
// Use interger
}
else if let floatVal = Float(result ?? "") {
// Use float
}
else if let doubleVal = Double(result ?? "") {
// Use double
}
else {
print("User has not entered integer, float or double")
}
Int.init(_ string) returns an optional, since its possible that the string is not an integer. So you can either make newStrings optional like var newSTrings = result.flatMap(Int.init) or nil coalesce it to zero or some other default var newSTrings = result.flatMap(Int.init) ?? 0

Efficient way to find all instances of Substring within a Swift String [duplicate]

This question already has answers here:
Swift find all occurrences of a substring
(7 answers)
Closed 5 years ago.
Swift 4 apparently has introduced a lot of new changes to String. I'm wondering if there is now a built-in method for finding all instances of a substring within a String.
Here's the kind of thing I'm looking for:
let searchSentence = "hello world, hello"
let wordToMatch = "hello"
let matchingIndexArray = searchSentence.indices(of: "wordToMatch")
'matchingIndexArray' would then be [0, 13]
import Foundation
let searchSentence = "hello world, hello"
var searchRange = searchSentence.startIndex..<searchSentence.endIndex
var ranges: [Range<String.Index>] = []
let searchTerm = "hello"
while let range = searchSentence.range(of: searchTerm, range: searchRange) {
ranges.append(range)
searchRange = range.upperBound..<searchRange.upperBound
}
print(ranges.map { "(\(searchSentence.distance(from: searchSentence.startIndex, to: $0.lowerBound)), \(searchSentence.distance(from: searchSentence.startIndex, to: $0.upperBound)))" })
outputs:
["(0, 5)", "(13, 18)"]

swift 2.2 basic, if statement doesn't compile [duplicate]

This question already has an answer here:
Error "{ expected after if statement"
(1 answer)
Closed 6 years ago.
Pardon me for beginner's question, Why this code got complained about { expected after if, the braces are already there
var years = Int(edtYears.text!)
if years !=nil {
//do something
}else {
//...
}
Thanks
You need to add space between both side of condition like if years != nil { or you can also write without space but the both side if years!=nil {
var years = Int("")
if years != nil {
//do something
}else {
//...
}
Never do like this. Make sure you do optional chaining otherwise you will surely get a crash.
if let text = edtYears.text, let convertToInt = Int(text){
print("Int \(convertToInt)")
}else{
print("Cannot convert")
}

In swift, how do I do this? [duplicate]

This question already has answers here:
Adding Thousand Separator to Int in Swift
(7 answers)
Closed 7 years ago.
My English is not enough to search the question. So, I have to write here. My integer is 600000000 for ex. I want to convert it like this: 600,000,000. How do I do this?
extension Int {
struct Number {
static let formatter = NSNumberFormatter()
}
var addThousandSeparator:String {
Number.formatter.groupingSeparator = "."
Number.formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
return Number.formatter.stringFromNumber(self)!
}
}
let myInteger = 600000000
let myIntegerString = myInteger.addThousandSeparator // "600.000.000"