将字符串与字符串数组进行比较并计算 Swift 中的匹配项

Comparing String against array of String and counting the matches in Swift

我正在尝试将一个字符串 (userInput) 与一个字符串数组 (groupS) 进行比较,以检查 userInput 中存在 groupS 中的多少项。

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."
var count = 0

func checking() -> Int {
    for item in groupA {
        // alternative: not case sensitive
        if userInput.lowercased().range(of:item) != nil {
            count + 1
        }
    }

    return count
}

func Printer() {
     print(count)
}

您的代码设计得不是很好,因为您使用了很多全局变量,但它可以通过一些小的更改工作:

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."

var count = 0
func checking() -> Int {
    for item in groupA {

        // alternative: not case sensitive
        if userInput.lowercased().range(of:item) != nil {
            count += 1  //Make this `count += 1`
        }
    }
    return count
}
func printer() {
    print(count)
}

//Remember to call `checking()` and `printer()`
checking()
printer()

另请注意,所有函数的名称都应以小写字母开头,因此 Printer() 应为 printer()

改为考虑此代码:

import UIKit

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."

//The `checking` function has been rewritten as `countOccurerences(ofStringArray:inString)`, 
//and now takes parameters and returns a value.
func countOccurrences(ofStringArray stringArray: [String],  inString string: String) -> Int {
    var result = 0
    for item in stringArray {

        // alternative: not case sensitive
        if string.lowercased().range(of:item) != nil {
            result += 1
        }
    }
    return result
}

//And the `printer()` function now takes parameter as well.
func printer(_ count: Int) {
    print("count = \(count)")
}

//Here is the code to use those 2 functions after refactoring
let count = countOccurrences(ofStringArray: groupA, inString: userInput)
printer(count)

要使上面的代码正常工作,您只需将第 18 行的 count + 1 更改为 count += 1 我已经在下面发布了完整的代码。

import Cocoa
import Foundation

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."


    var count = 0
    func checking() -> Int {


        for item in groupA {


            // alternative: not case sensitive
            if userInput.lowercased().range(of:item) != nil {
                count += 1
            }


        }

        return count
    }



    func Printer() {
        print(count)
    }

    checking()
    Printer()