3

I'm currently trying to determine the best way to compare a string value to an array of Strings. Here's the problem...

I'm building a converter between binary, decimal and hex values that share the same keypad. I want to check the input and depending on the mode, let it through or not (e.g. binary more only allows 1 and 0, decimal 0-9 and hex 0-F).

I can do this by saying:

if (digit == binaryDigits[0]) || (digit == binaryDigits[1]) {
// do something
}

but that's not very practical when it comes to the decimal and hex values.

Basically I would like a way to check a given String against all values within a String Array.

1

3 Answers 3

5

You can use the contains() method:

var strings = ["Test", "hi"]
if contains(strings , "hi") {
    println("Array contains string")
}
Sign up to request clarification or add additional context in comments.

Comments

4

Use stringArray.contains(string)

Example:

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
print(cast.contains("Marlon")) 
// Prints "true"
print(cast.contains("James"))  
// Prints "false"

Visit https://developer.apple.com/documentation/swift/array/2945493-contains

3 Comments

Thanks, that's the same as what Christian suggested
Not exactly... contains(array, string) did not work for me since it has been changed to array.contains(string)
Oh yeah I'm sorry, didn't notice that difference. I just saw 'contains' and assumed it was the same. Apologies... Marked yours as the answer as it's up-to-date
0

This may not be the most elegant solution but it's clear and concise:-

func isValidHex( input: String ) -> Bool {
    let hset:NSCharacterSet = NSCharacterSet(charactersInString:"0123456789ABCDEF")
    return (countElements(input.stringByTrimmingCharactersInSet(hset)) == 0)
}

func isValidDecimal( input: String ) -> Bool {
    let hset:NSCharacterSet = NSCharacterSet(charactersInString:"0123456789")
    return (countElements(input.stringByTrimmingCharactersInSet(hset)) == 0)
}

func isValidBinary( input: String ) -> Bool {
    let hset:NSCharacterSet = NSCharacterSet(charactersInString:"01")
    return (countElements(input.stringByTrimmingCharactersInSet(hset)) == 0)
}

2 Comments

Thanks for the idea! I think I'll use the contains() method some others posted but thanks for a different way of doing it
Think I misunderstood your question. I thought you wanted to validate if strings were binary, decimal or hex.

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.