Basu
Basu

Reputation: 763

Iterating over string in Swift to fetch mobile number

I'm trying to fetch mobile numbers from a long list of string which contains mobile number written in it separated by comma.

E.g:

8809394847, 9988338847, 9933883384, 8833938373

In my code, I have a function which accepts mobile number to do a particular job. My entire string is stored in a variable called inputData.

I tried using this code:

let mob = inputData.index(of: " ") ?? inputData.endIndex
    let mobile = inputData[..<mob]
    MyJob(phone: mobile). //Function that accepts mobile number

But it makes no sense.

My original code :

@IBAction func clickButton(_ sender: UIButton) {
    inputData = textView.text!

    MyJob(phone: mobile).  //Calling function

}

I need to run some kind of loop inside the clickButton function to fetch the mobile numbers and send it to the MyJob function one by one.

Upvotes: 0

Views: 74

Answers (4)

Sandeep
Sandeep

Reputation: 110

You can use split function to get array of substrings as [subStrings] like

let str = "8809394847,9988338847,9933883384, 8833938373"
let arrayOfNumbers = str.split(separator: ",")
print(arrayOfNumbers)

output: ["8809394847", "9988338847", "9933883384", "8833938373"]

iterate this array and send it to the MyJob function one by one.

Hope this helps.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100533

You better try components separation string function

@IBAction func clickButton(_ sender: UIButton) {

  inputData = textView.text!

  var mobileNumbers = inputData.components(separatedBy: ",")

  for mobile in mobileNumbers {
     MyJob(phone: mobile) //Calling function
  }

 }

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54745

You can simply use String.components(separatedBy:) to split your String into separate phone numbers.

@IBAction func clickButton(_ sender: UIButton) {
    let numbersString = textView.text!
    let numbers = numbersString.components(separatedBy: ", ")
    for number in numbers {
        MyJob(phone: number)
    }
}

Upvotes: 1

vadian
vadian

Reputation: 285160

Use components(separatedBy with parameter ", " to make an array then use a loop for example

let string = "8809394847, 9988338847, 9933883384, 8833938373"
let phoneNumbers = string.components(separatedBy: ", ")
for phoneNumber in phoneNumbers {
    MyJob(phone: phoneNumber)
}

Upvotes: 1

Related Questions