swift - What's the difference between if nil != optional … and if let _ = optional … -
i need test if expression returns optional nil
. seems no-brainer, here code.
if nil != self?.checklists.itempassingtest({ $0 === note.object }) { … }
which, reason, looks unpleasant eye.
if let item = self?.checklists.itempassingtest({ $0 === note.object }) { … }
looks better me, don't need item, need know if 1 returned. so, used following.
if let _ = self?.checklists.itempassingtest({ $0 === note.object }) { … }
am missing subtle here? think if nil != optional …
, if let _ = optional …
equivalent here.
update address concerns in answers
i don't see difference between
nil != var
,var != nil
, although usevar != nil
. in case, pushing!= nil
after block gets boolean compare of block mixed in boolean compare of if.the use of wildcard pattern should not surprising or uncommon. used in tuples
(x, _) = (10, 20)
, for-in loopsfor _ in 1...5
, case statementscase (_, 0):
, , more (note: these examples taken swift programming language).
this question functional equivalency of 2 forms, not coding style choices. conversation can had on programmers.stackexchange.com.
after time, swift 2.0 makes moot
if self?.checklists.contains({ $0 === note.object }) ?? false { … }
after optimization, 2 approaches same.
for example, in case, compiling both following swiftc -o -emit-assembly if_let.swift
:
import darwin // using arc4random ensures -o doesn’t // ignore if statement let i: int? = arc4random()%2 == 0 ? 2 : nil if != nil { println("set!") }
vs
import darwin let i: int? = arc4random()%2 == 0 ? 2 : nil if let _ = { println("set!") }
produces identical assembly code:
; call arc4random callq _arc4random ; check if lsb == 1 testb $1, %al ; if is, skip println je lbb0_1 movq $0, __tv6if_let1igsqsi_(%rip) movb $1, __tv6if_let1igsqsi_+8(%rip) jmp lbb0_3 lbb0_1: movq $2, __tv6if_let1igsqsi_(%rip) movb $0, __tv6if_let1igsqsi_+8(%rip) leaq l___unnamed_1(%rip), %rax ; address of "set!" literal movq %rax, -40(%rbp) movq $4, -32(%rbp) movq $0, -24(%rbp) movq __tmdss@gotpcrel(%rip), %rsi addq $8, %rsi leaq -40(%rbp), %rdi ; call println callq __tfss7printlnu__fq_t_ lbb0_3: xorl %eax, %eax addq $32, %rsp popq %rbx popq %r14 popq %rbp retq
Comments
Post a Comment