如何在更简单的情况下更正此代码

时间:2017-06-14 23:47:22

标签: swift string variables if-statement int

我只是在Xcode的游乐场测试一些代码,而我正试图学习如何使用if语句。另外我该如何更正此代码?编译时我遇到了一些错误。其中一个是"无法分配价值:'&&'返回不可变值"。是否有可能在使代码更正确的同时使代码更具可读性和简单性?

我写的代码:

var minutes = 10

var name = "Marcus"

var hours = 2

var status : String = " "

if minutes = nil && hours = !nil {

    status = "\(name) spent \(hours) hrs online"

} else if minutes = !nil && hours = nil {

    status = "\(name) spent \(minutes) mins online"

} else if minutes = !nil && hours = !nil {

    status = "\(name) spent \(hours) hrs & \(minutes) mins online"

}

print(status)

2 个答案:

答案 0 :(得分:2)

如果您定义hoursminutes,那么它们将永远不会为零,因此无需检查。你必须将它们声明为选项。 switch为您提供了一个干净的解决方案:

var hours: Int? = 2
var minutes : Int? = 10
var name = "Marcus"

var status = ""
switch (hours, minutes) {
case (nil, nil):
    status = "both hours and minutes cannot be nil"
case (_, nil):
    status = "\(name) spent \(hours!) hrs online"
case (nil, _):
    status = "\(name) spent \(minutes!) mins online"
default:
    status = "\(name) spent \(hours!) hrs & \(minutes!) mins online"
}

print(status)

答案 1 :(得分:1)

使用=代替==会导致一些错误。

当变量不是选项时,不会对nil进行测试也会触发警告。

这里有一些代码可以编译你现在可以使用逻辑的地方:

var minutes: Int? = 10
var name: String? = "Marcus"
var hours: Int? = 2
var status : String = "Hello"

if minutes == nil && hours != nil {
    status = "\(name) spent \(hours) hrs online"
} else if minutes != nil && hours == nil {
    status = "\(name) spent \(minutes) mins online"
} else if minutes != nil && hours != nil {
    status = "\(name!) spent \(hours!) hrs & \(minutes!) mins online"
}

print(status)