Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift中的Sum和For循环在一起_Swift - Fatal编程技术网

Swift中的Sum和For循环在一起

Swift中的Sum和For循环在一起,swift,Swift,我想知道给定集合中有多少个常用字符 Input: J = "aA", S = "aAAbbbb" Output: 3 在用于此的python解决方案中,如下所示: lookup = set(J) return sum(s in lookup for s in S) 我在Swift中有以下解决方案,它可以工作,但看起来太冗长了。我想学一种简单的方法 class Solution { func checkInItems(_ J: String, _ S: String) -> In

我想知道给定集合中有多少个常用字符

Input: J = "aA", S = "aAAbbbb"
Output: 3
在用于此的python解决方案中,如下所示:

lookup = set(J)
return sum(s in lookup for s in S)
我在Swift中有以下解决方案,它可以工作,但看起来太冗长了。我想学一种简单的方法

class Solution {
    func checkInItems(_ J: String, _ S: String) -> Int {
        let lookup = Set(J) ;
        var sy = 0;
        for c in S
        {
            if lookup.contains(c)
            {
               sy += 1;                
            }
        }        
        return sy;
    }
}
你可以试试

class Solution {
  func checkInItems(_ J: String, _ S: String) -> Int {
    let lookup = Set(J)
    return S.filter { lookup.contains($0) }.count
  }
}
你可以试试

class Solution {
  func checkInItems(_ J: String, _ S: String) -> Int {
    let lookup = Set(J)
    return S.filter { lookup.contains($0) }.count
  }
}
作为的一个小变体,您可以使用
reduce
计算匹配元素的数量,而不创建中间元素 数组:

在Swift 5中,将有一个用于此目的的
计数(其中:)
顺序方法, 请参阅。

作为的一个小变体,您可以使用
减少
计算匹配元素的数量,而不创建中间元素
数组:

在Swift 5中,将有一个用于此目的的
计数(其中:)
顺序方法,
请参阅。

您想知道任何输入字符在您搜索的字符串中出现的频率吗?您想知道任何输入字符在您搜索的字符串中出现的频率吗?