简体   繁体   中英

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM