Tom
Tom

Reputation: 81

How do I find the character count of each item in an array

I'm writing a function that prints string values from a dictionary that have a character count over 8. Below is what I have so far, but I'm not sure how to formulate my where condition so that it looks at the number of characters in each string value in the array.

var stateCodes = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"]

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
let fullStateNames = Array(stateCodes.values)

for _ in fullStateNames where fullStateNames.count > 8 {
    print(fullStateNames)
    return fullStateNames
}

return fullStateNames
}

printLongState(stateCodes)

Upvotes: 0

Views: 1351

Answers (3)

Rashwan L
Rashwan L

Reputation: 38833

Just filter your result instead of using a for-loop:

If you want to return a dictionary use the following:

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
    let overEightChars = stateCodes.filter({ $0.value.characters.count > 8 })
    return overEightChars
}

If you want to return an array of Strings use the following:

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
    return dictionary.values.filter { $0.characters.count > 8 }
}

Upvotes: 1

Nirav D
Nirav D

Reputation: 72420

If you want to go with for loop then you can make it like this way.

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {
    var fullStateNames = [String]()
    for (_, value) in dictionary where value.characters.count > 8 {
        fullStateNames.append(value)
    }
    return fullStateNames
}

But this is not Swifty way in Swift what you can do is you can use flatMap with your Dictionary to make array of string or use dictionary.values.filter

Using flatMap with dictionary

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {  
    return dictionary.flatMap { $1.characters.count > 8 ? $1 : nil }
}
// Call it like this way.
var stateCodes = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"] 
print(printLongState(stateCodes)) //["Wisconsin", "New Jersey"]

Using filter on dictionary.values

func printLongState (_ dictionary: [String: String]) -> (Array<Any>) {  
    return dictionary.values.filter { $0.characters.count > 8 }
}

Upvotes: 4

Jan
Jan

Reputation: 2293

Try using filter together with characters.count like this:

var states = ["NJ": "New Jersey", "CO": "Colorado", "WI": "Wisconsin", "OH": "Ohio"]

states.filter({ (_, value) -> Bool in
    return value.characters.count > 8
}).map({ (_, value) in
    print(value)
})

Upvotes: 1

Related Questions