如何在Swift中向数组添加可选值

时间:2019-04-11 11:42:05

标签: ios swift

我在将可选值附加到Swift中的数组时遇到问题。我写的视图是为健身房创建例程的。但是我的Routine对象没有被实例化。

我有使用其他编程语言的经验,但是我对Swift和可选语言还很陌生。

我的ViewController包含一个可选变量:

var routine: Routine?

其中Routine类包含以下内容:

name: String
exerciseList: [String]()
numOfSets: [Int]()

当我准备将新创建的例程发送到另一个ViewController时,我从用户输入中获取值来编辑对象的字段。

let name = routineName.text ?? ""
let numberOne = Int(numOfSetsOne.text ?? "0") //numOfSetsOne is a text label
routine?.exerciseList.append(selectedExerciseOne!) //Haven't tested to see if this works yet
routine?.numOfSets[0] = numberOne! //This line is not working 
routine = Routine(name: name)

为了进行一些调试,我将打印语句放在行的两边,如下所示:

print ("numberOne Value: \(numberOne!)")
routine?.numOfSets[0] = numberOne!
print ("numOfSets[0] Value: \(routine?.numOfSets[0])")

我希望第二个print语句的输出与第一个相同。但是终端输出:

numberOne Value: 3
numOfSets[0] Value: nil

有人知道这里出了什么问题吗? 谢谢

2 个答案:

答案 0 :(得分:3)

您已声明一个属性,其中可能包含一个Routine,但是在尝试使用该属性之前,尚未为该属性分配Routine的实例。

例如,这表示

routine?.numSets[0] = numberOne! 

不执行任何操作-routinenil,因此该语句被跳过。

您应该为您的init类创建一个合适的Routine函数,并使用该函数创建一个新的Routine并将其分配给routine

例如:

class Routine {
    var name: String
    var exerciseList = [String]()
    var numberOfSets = [Int]()

    init(named: String) {
        self.name = named
    }
}

那你可以说

let name = routineName.text ?? ""
let numberOne = Int(numOfSetsOne.text ?? "0") 
self.routine = Routine(named: name)
self.routine?.numberOfSets.append(numberOne!)

协调相关的数组可能会有些混乱,因此我将使用单个数组:

struct ExerciseSet {
    let exerciseName: String
    let sets: Int
}


class Routine {
    var name: String
    var exerciseList = [ExerciseSet]()

    init(named: String) {
        self.name = named
    }
}

答案 1 :(得分:1)

您的Routine在分配值之前未初始化

尝试

let name = routineName.text ?? ""
let numberOne = Int(numOfSetsOne.text ?? "0") 

routine = Routine(name: name)

routine?.exerciseList.append(selectedExerciseOne!) 
routine?.numOfSets[0] = numberOne!