1

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

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)
}
4

2 回答 2

1

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

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)
于 2018-08-01T01:40:17.270 回答
0

要使上述代码正常工作,您只需将count + 1第 18 行更改为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()
于 2018-08-01T01:41:11.597 回答