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.

Idan
  • 5,405
  • 7
  • 35
  • 52
SimonTheEngineer
  • 733
  • 1
  • 7
  • 19
  • Is this what you need: [How to check if an element is in an array](http://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array) ? – Martin R Jan 30 '15 at 17:03

3 Answers3

5

You can use the contains() method:

var strings = ["Test", "hi"]
if contains(strings , "hi") {
    println("Array contains string")
}
Christian
  • 22,585
  • 9
  • 80
  • 106
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

AW5
  • 406
  • 3
  • 12
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)
}
Echelon
  • 7,306
  • 1
  • 36
  • 34
  • Thanks for the idea! I think I'll use the contains() method some others posted but thanks for a different way of doing it – SimonTheEngineer Jan 30 '15 at 21:04
  • Think I misunderstood your question. I thought you wanted to validate if strings were binary, decimal or hex. – Echelon Feb 02 '15 at 17:25