您的代码设计得不是很好,因为您使用了很多全局变量,但它可以进行一些小的更改:
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)