如何使用可选绑定检查负数表达式中的多个值?

时间:2018-12-08 10:07:27

标签: swift optional-binding

我想检查两个可选变量是否全部为空。 例如,在C中,

int n1 = 1;
int n2 = 2;
if( n1!=0 && n2!=0 ) {
     //  do something.
}

在Swift中有什么方法可以做到这一点? 谢谢。

3 个答案:

答案 0 :(得分:1)

您所说的可选绑定实际上只是具有多个条件的 if语句可选绑定用于当您要从可以为nil的常量/变量中定义常量/变量时。如果不是,则执行if语句中的代码。

但是您需要使用可选类型定义两个值。您可以使用问号Type?进行此操作,然后可以检查两个值是否都不为nil

您在Swift中的代码:

let n1: Int? = 1
let n2: Int? = 2
if n1 == nil && n2 == nil {
    //  do something.
}

答案 1 :(得分:1)

只需使用Public Class Form1 Public p As New List(Of Point) Public direction As eDircetion = eDircetion.Up Public Enum eDircetion Up Down Left Right End Enum Public sizey As Integer = -1 Public tik As Integer = 0 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load newpart() newpart() newpart() head.Interval = 500 head.Start() End Sub Public Sub square(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) e.Graphics.Clear(Color.Black) For a = 0 To sizey e.Graphics.FillRectangle(Brushes.Aqua, p(a).X, p(a).Y, 20, 20) Next End Sub Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown If e.KeyCode = Keys.D Then direction = eDircetion.Right ElseIf e.KeyCode = Keys.A Then direction = eDircetion.Left ElseIf e.KeyCode = Keys.W Then direction = eDircetion.Up ElseIf e.KeyCode = Keys.S Then direction = eDircetion.Down End If End Sub Private Sub Form1_Paint(ByVal sender As Object, ByVal e _ As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint square(sender, e) End Sub Private Sub clock_Tick(sender As Object, e As EventArgs) Handles head.Tick 'THIS! For i = p.Count - 1 To 1 Step -1 p(i) = p(i - 1) Next Select Case direction Case eDircetion.Up p(0) -= New Size(0, 20) Case eDircetion.Down p(0) += New Size(0, 20) Case eDircetion.Left p(0) -= New Size(20, 0) Case eDircetion.Right p(0) += New Size(20, 0) Case Else : Throw New Exception("Something went wrong") End Select 'Me.Refresh() me.Invalidate() 'This is faster. Me.Update() 'For b = 0 To sizey - 1 ' If p(b).Y - p(b + 1).Y = 0 Then ' p(b + 1).X = p(b + 1).X + (p(b).X - p(b + 1).X) ' ElseIf xx(b) - xx(b + 1) = 0 Then ' yy(b + 1) = yy(b + 1) + (yy(b) - yy(b + 1)) ' If neww = True Then ' neww = False ' Exit For ' End If ' End If 'Next End Sub Sub newpart() p.Add(New Point(100, 100)) sizey = sizey + 1 Return End Sub End Class 运算符:

&&

答案 2 :(得分:1)

您可以通过将两个可选内容与nil进行比较来检查两个可选内容是否为nil

let n1: Int? = nil
let n2: Int? = nil
if n1 == nil, n2 == nil {
    print("Nil all the way")
}

用逗号分隔条件等同于使用&&

这是使用元组的替代方法:

if (n1, n2) == (nil, nil) {
    print("Nil all the way")
}