String Convert into double in swift 4.1 [duplicate] - swift

This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 4 years ago.
let getLongijson: String = "67.0011"
let getlatijson: String = "24.8607"
let jsonlong = (getLongijson as NSString).doubleValue
let jsonlat = (getlatijson as NSString).doubleValue
Error i am Facing this
Cannot use instance member 'getLongijson' within property initializer; property initializers run before 'self' is available

You like this to convert String into Double:
let getLongijson: String = "67.0011"
let getlatijson: String = "24.8607"
let jsonlong = Double(getLongijson)
let jsonlat = Double(getlatijson)

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

Swift 4 error with appending data into an array [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
In my app I have a group of arrays that I append with data from an API. The method is as follows:
let noOfCountries = APIData.data.count
while self.countries < noOfCountries{
self.idArray.append(APIData.data[self.countries].id!)
self.countryIntroArray.append(APIData.data[self.countries].countryIntroTab!)
self.countryNameArray.append(APIData.data[self.countries].countryName!)
self.flagArray.append(APIData.data[self.countries].countryFlag!)
self.countryEventsArray.append(APIData.data[self.countries].countryEventsTab!)// App crashes here with this error: Unexpectedly found nil while unwrapping an Optional value
self.countries += 1
}
For some reason the app crashes at at self.countryEventsArray.append. The arrays are declared as follows:
var idArray = [Int]()
var countryIntroArray = [String]()
var countryNameArray = [String]()
var flagArray = [String]()
var countryEventsArray = [String]()
The structs are set as such:
let id: Int?
let countryName: String?
let countryFlag: String?
let countryIntroTab: String?
let countryEventsTab: String?
What is it that I'm doing wrong? If I remove the exclamation from self.countryEventsArray the app will not run at all.
you shouldn't append api data into array without any data exist check
use the same code for check
if let myData = APIData.data[self.countries].countryEventsTab {
self.countryEventsArray.append(myData)
}

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

Reversing a string in Swift [duplicate]

This question already has answers here:
Reversing the order of a string value
(13 answers)
Closed 5 years ago.
Needed to reverse a swift string, managed to do so with this.
var str = "Hello, playground"
let reactedText = str.characters.reversed()
let nowBackwards = Array(reactedText)
let answer = String(nowBackwards)
And since I find nothing on SO in the subject I post it for some positive votes :) or indeed a better [shorter, as in different] solution.
Assuming you are using Swift 4 :
let string = "Hello, playground"
let reversedString = String(string.reversed())
Since in Swift 4, Strings are Character arrays again, you can call reversed on the String itself and the result will be of type [Character], from which you can initialize a String.
let stringToBeReversed = "Hello, playground"
let reversedString = String(stringToBeReversed.reversed()) //"dnuorgyalp ,olleH"
reversed method is available in String library
let str = "Hello, world!"
let reversed = String(str.reversed())
print(reversed)

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"