[英]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. 我正在写一个函数,该函数从字符数超过8的字典中打印字符串值。这是到目前为止的内容,但是我不确定如何公式化where条件,以便它查看字符数在数组中的每个字符串值中。
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. 如果要使用for循环,则可以像这样进行操作。
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
但这不是Swift中的Swifty方法,您可以做的是可以在您的
Dictionary
使用flatMap
来创建string
数组或使用dictionary.values.filter
Using flatMap with dictionary 在字典中使用flatMap
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
在
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
: 只是
filter
您的结果,而不是使用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: 尝试将
filter
与characters.count
一起使用,如下所示:
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)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.