组件由字符串崩溃app swift分隔

时间:2016-02-16 13:59:45

标签: ios iphone swift

我有一个应用程序,通过使用componentSeparatedByString(",")将textField输入转换为Int的数组但是当我在文本字段中输入多个逗号时应用程序崩溃,试图在线找到解决方案,但没有运气,我该如何解决这个问题?我可以通过检查characters.first ==","来防止它崩溃。 || characters.last ==",",但不是连续的逗号。

Tue Feb 16 07:05:04 EST 2016    ERROR   ZooKeeper Server: Using config: /opt/zookeeper/zookeeper-3.4.6/bin/../conf/zoo.cfg
Tue Feb 16 07:05:04 EST 2016    ERROR   ZooKeeper Server: JMX enabled by default
Tue Feb 16 07:05:04 EST 2016    INFO    Process started via: /opt/zookeeper/zookeeper-3.4.6/bin/zkServer.sh
Tue Feb 16 07:05:03 EST 2016    INFO    Kill attempted result: 0
Tue Feb 16 07:05:03 EST 2016    INFO    Attempting to start/restart ZooKeeper
Tue Feb 16 07:05:03 EST 2016    INFO    Attempting to stop instance
Tue Feb 16 07:05:03 EST 2016    INFO    Restarting down/not-serving ZooKeeper after 60037 ms pause
Tue Feb 16 07:04:33 EST 2016    INFO    ZooKeeper down/not-serving waiting 30026 of 40000 ms before restarting
Tue Feb 16 07:04:05 EST 2016    INFO    ZooKeeper Server: Starting zookeeper ... STARTED
Tue Feb 16 07:04:04 EST 2016    ERROR   ZooKeeper Server: Using config: /opt/zookeeper/zookeeper-3.4.6/bin/../conf/zoo.cfg
Tue Feb 16 07:04:04 EST 2016    ERROR   ZooKeeper Server: JMX enabled by default

1 个答案:

答案 0 :(得分:3)

以下是我将使您的代码工作的方法。这里重要的是一般的想法,而不是我正在使用的具体例子(虽然它应该适合你)。

首先,让我们安全地打开文本标签:

if let text = circuitNumbersTextField.text {

}

现在我们避免使用circuitNumbersTextField.text!,我们知道错误不会来自那里。

然后我们在组件中剪切句子:

if let text = circuitNumbersTextField.text {
    let circuits = text.componentsSeparatedByString(",")

}

我们使用flatMap安全地解包Int()返回的Optionals:

if let text = circuitNumbersTextField.text {
    let circuits = text.componentsSeparatedByString(",")
    let circuitNumbers = circuits.flatMap { Int($0) }
    // circuitNumbers will only contain the successfully unwrapped values
}

您的代码段:

if let text = circuitNumbersTextField.text {
    let circuits = text.componentsSeparatedByString(",")
    let circuitNumbers = circuits.flatMap { Int($0) }
    if (circuits.first != "," && circuits.last != ",") || circuits.first != "," || circuits.last != "," {
        // condition is met
    } else {
        // condition is not met
    }
}

现在,您可以安全地在此代码块中使用circuitNumbers而不会崩溃。