Swift Grammar-where keyword detailed _swift basics

Source: Internet
Author: User

In swift syntax the WHERE keyword acts as a where in SQL, that is, additional conditional judgment.


1, in the collection traversal use where, if the condition is true, execute code block, false when not executing code block.

    Let array = [0, 1, 2, 3, 4, 5, 6]
    
    //Use switch traversal
    Array.foreach {
        switch $ {case let
        x where x > 3:   Where is equivalent to
            the judgment condition print ("second half")
        default:
            print ("Default value")
        }
    
    ///
    Array where value > 2 {
        print (value)   /Output 3 4 5 6
    }
    
    for (index, value) in array.enumerated () where I Ndex > 2 && value > 3 {
        print ("Subscript: \ (index), value: \ (value)")
    }

Output:

Default value default value default value the second half of the second half paragraph
3
4
5
6 subscript
: 4, Value:
4 subscript: 5, Value: 5 subscript
: 6, Value: 6

2, in the supplementary abnormal Do/catch use



3, where the protocol uses, only the base class implements the current protocol to add extensions. In other words, multiple classes implement the same protocol, which adds extensions to these classes, depending on the class name, respectively.

Protocol Someprotocol {
    func somemethod ()
}

class A:someprotocol {let
    A = 1
    
    func somemethod () {
  
   print (' Call SomeMethod ')
    }

class B {let
    a = 2
}

//base Class A inherits the Someprotocol protocol to add an extension
Extension Someprotocol where self:a {
    func Showparama () {
        print (SELF.A)
    }
}
//Inverse, does not conform to the Where condition
extension Someprotocol where self:b {
    func Showparama () {
        print (SELF.A)
    }
} let
obja = a () let
objb = B ()  //class B is not implemented Someprotocol, all without protocol method
Obja.showparama ()  //Output 1

  


Summary: Where keywords can be used in collection traversal, switch/case, protocols, Swift3 where the If let and guard scenes have been replaced by Swift4 commas, such as if Let A=param, a>10 ( The former needs to judge whether it is nil, which is equivalent to the Where condition.





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: