【问题标题】:How to check if string is empty in swift 3? [duplicate]如何在swift 3中检查字符串是否为空? [复制]
【发布时间】:2020-02-13 17:29:53
【问题描述】:

好的,所以我正在尝试快速制作康威的生活游戏。我正在尝试创建一个 UI,允许用户输入开始时的坐标。然而,当他们完成后,我试图得到它,所以他们点击进入,那里什么都没有,它会移动。我说“是!”表示我试图获取代码的位置,但我无法将其设置为“是!”,当我将其输入为空时,我得到一个索引越界错误。

func splitStrPar(_ expression: String) -> [String] {
    return expression.split{$0 == " "}.map{ String($0) }
}

func getCommand() -> [String] {
    return splitStrPar(readLine()!)
}

func setup() {
    print("Enter x y coordinates of living cells, blank line when done")
    print("Coor" , terminator : ":")
    var command = getCommand()
    print(command[0])
    while(command[0] != "") {
        print("Coor" , terminator : ":")
        command = getCommand()
    }
    print("yes!")
}

【问题讨论】:

  • 我建议将 command[0].isEmpty 替换为 command.first?.isEmpty 。这样如果数组为空,就不会出现这样的错误。或者在查找索引零之前检查数组是否不为空
  • Swift 3 真的很老了。你真的应该升级。
  • 如何检查数组是否为空?

标签: swift


【解决方案1】:

你可以使用这个条件来检查空数组

if "your array name" == []{}
if "your array name".isEmpty {}

也可以使用这个条件检查空字符串

if "your string" == "" {}

【讨论】:

    【解决方案2】:

    检查是否为空很简单。示例代码:

    // Initialize the Array
    
    var myArray = [1,2,3]
    
    // Check if it is empty
    
    if myArray.isEmpty {
      print("My Array, it's empty")
    }
    else {
      print("No, My Array not empty")
    }
    

    【讨论】:

      【解决方案3】:

      只需使用此代码:

      let fullList = [1,2,3]
      let emptylist = [Int]()
      if fullList.isEmpty{
          print("This will not be printed as it is false.")
      }
      if emptylist.isEmpty{
          print("This will be printed as it is true.")
      }
      

      如果数组为空,函数 array.isEmpty 将返回 true。注意emptylist数组是空的。

      【讨论】:

        猜你喜欢
        • 2011-01-23
        • 2016-01-25
        • 1970-01-01
        • 1970-01-01
        • 2013-01-30
        • 2011-11-25
        • 2012-03-23
        相关资源
        最近更新 更多