簡體   English   中英

如何找到數組中每個項目的字符數

[英]How do I find the character count of each item in an 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)

如果要使用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中的Swifty方法,您可以做的是可以在您的Dictionary使用flatMap來創建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 }
}

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

嘗試將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)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM