Swift Convert comma separated string to NSMutableArray [duplicate] - swift

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 7 years ago.
I have the following string
var points = "4,5"
I would like to convert to a mutable array so it becomes [4,5]
I tried the following but it did not work
var points = "4,5"
var selectedArray : NSMutableArray = [points]

Swift 2:
Here you go:
var points = "4,5"
var pointsArr = split(points) {$0 == ","}
or
var pointsArr = points.componentsSeparatedByString(",")
Source: Swift: Split a String into an array
Swift 3:
as gomfucius mentioned:
var arr = points.components(separatedBy: ",")

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.

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"