【问题标题】:I have problem with comparing Strings in Swift我在比较 Swift 中的字符串时遇到问题
【发布时间】:2020-04-21 21:42:18
【问题描述】:

我想检查一个字符串,看看它是否包含一个字母。代码如下:

func CheckLetter(letter:String,word:String) -> String{

    var checkFlag = false
    var tempWord = [""]

    for n in 0...(word.count-1){
        if tempWord[n] == letter[0]{

        }
    }

}

错误是: 'subscript(_:)' 不可用:不能用 Int 为 String 下标,请改用 String.Index。

【问题讨论】:

  • 这不是您遇到的错误。你得到了"Binary operator '==' cannot be applied to operands of type 'String' and 'Character'"。如果您修复二元运算符错误,您所描述的错误将显示。你的目标是什么?您是否要检查字符串是否包含字符?
  • 这能回答你的问题吗? stackoverflow.com/questions/24034043/…
  • 仅供参考,方法和变量名称应为小写。只有类名是大写的。

标签: swift string if-statement compare


【解决方案1】:

结帐Swift String Cheat Sheet, by Keith Harrison

你可以使用:

func checkLetter(letter: String, word: String) -> String {

    return word.contains(letter).description
}

【讨论】:

  • 你的答案是最接近的,但有件事我忘了说,如果这个词包含这个字母,我想知道那个字母的索引是什么?
  • @SinaSB 我添加了一篇文章的链接,您会发现它很有用。
【解决方案2】:

试试这个!!!

func CheckLetter(letter:String,word:String) -> Bool{
        var checkFlag = false
        if word.contains(letter) {
            checkFlag = true
        }
        return checkFlag
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多