SimonTheEngineer
SimonTheEngineer

Reputation: 743

Compare String against String Array

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.

Upvotes: 3

Views: 8251

Answers (3)

AW5
AW5

Reputation: 426

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

Upvotes: 4

Echelon
Echelon

Reputation: 7922

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)
}

Upvotes: 0

Christian
Christian

Reputation: 22343

You can use the contains() method:

var strings = ["Test", "hi"]
if contains(strings , "hi") {
    println("Array contains string")
}

Upvotes: 5

Related Questions