如何查找数组中每个项目的字符数

时间:2017-06-20 17:01:02

标签: arrays swift loops where

我正在编写一个函数,用于打印字符数大于8的字典中的字符串值。以下是我到目前为止的情况,但我不确定如何制定我的条件,以便它查看数组中每个字符串值中的字符数。

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)

3 个答案:

答案 0 :(得分:4)

如果你想使用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
}

但这不是Swift的Swift方式,你可以做的是你可以flatMap使用Dictionary制作string数组或使用dictionary.values.filter

将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"]

dictionary.values

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

答案 1 :(得分:1)

只需filter您的结果,而不是使用for-loop

如果您想要返回字典,请使用以下内容:

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

如果要返回字符串数组,请使用以下命令:

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

答案 2 :(得分:1)

尝试将filtercharacters.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)
})