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

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"

Related

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

How do you split a string at every n-th character in Swift? [duplicate]

This question already has answers here:
How to split a string into substrings of equal length
(13 answers)
Closed 4 years ago.
Like the question says, if I have:
XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28
How can I split this string at every 8th character to get:
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSA
Implement this function
extension String {
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
call it this way,
let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)
Output will be like this,
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28
This will be generic solution if you want to add any character instead of space, it will work.

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)"]

Removing "Optional" in Swift 4 [duplicate]

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"
}

Expeceted Declaration when using for loop [duplicate]

This question already has an answer here:
Expected Declaration Error using Swift
(1 answer)
Closed 5 years ago.
Im just trying to use a for loop to run through some code, but I get an Expected declaration error.
var index = 0
for( i in 0..< array.count) {
let commonPrefix = array[i].commonPrefixWithString(array[index], options: .CaseInsensitiveSearch)
if (countElements(commonPrefix) == 0 ) {
let string = array[index].uppercased();
let firstCharacter = string[string.startIndex]
let title = "\(firstCharacter)"
let newSection = (index: index, length: i - index, title: title)
sections.append(newSection)
index = i
}
}
Help
That's not how you write a for loop in Swift. What you want is this
for i in 0..<array.count {
// the loop inner body
}