0

I have a string "25% off", i want to extract only value 25 from this, how can i extract it in swift, previously i had done with objective c but in swift hoe can we do that? I have tried this code but failed,

 let discount = UserDefaults.standard.string(forKey: "discount")
    print(discount)
    let index = discount?.index((discount?.startIndex)!, offsetBy: 5)
    discount?.substring(to: index!)
    print(index)

How can i get 25 from it?

1
  • Explain what you mean by the code "failed," and since you said you've done it with Objective-C, I'd add that code too. Commented Feb 28, 2018 at 20:07

2 Answers 2

1

A smart solution is to find the range of all consecutive digits from the beginning of the string with Regular Expression, the index way is not very reliable.

let discount = "25% off"
if let range = discount.range(of: "^\\d+", options: .regularExpression) {
    let discountValue = discount[range]
    print(discountValue)
}

You can even search for the value including the percent sign with pattern "^\\d+%"

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a numeric character set to just extract the number from that string:

let discount = "25% off"
let number = discount.components(separatedBy: 
             CharacterSet.decimalDigits.inverted).joined(separator: "") 
print(number) // 25

Just be sure to use the inverted var, otherwise you will get the non-numbers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.