What Does Operator _ , ! , ? , ?? Means In Swift

If you are a beginner of iOS swift programming, you may be confused by some strange swift operator, such as _, !, ?, ??. This article will tell you what dose those strange swift operator means one by one.

  1. _ : The under score operator is usually used in swift function definition. It is used to replace the function parameter’s external label. So when you call the swift function, you do not need to use function parameter ‘s external label name to specify which parameter this value is assigned to, just pass the parameter in function parameters definition order. You can read article iOS Swift Function External And Internal Parameter Name Example to learn more.
  2. ? : The question mark operator is used to define a swift variable as optional variable, which means this variable do not need to be initialized when define it. If do not initialize it with a default value, then it’s default value is nil which is similar with null in java. If the optional variable has child optional variable, then you can use optional chaining to refer it such as a?.b?.c?.text
  3. ! : If you want to get an optional variable’s original value, you should add ! mark at the variable name’s end to force unwrap it, then you can use it’s original value. Please read article How To Fix Error ‘Value Of Optional Type Must Be Unwrapped To A Value Of Type’ In Swift to learn more.
  4. ?? :  This operator is called nil coalescing operator. It is used to return first none nil value of the two swift variables. For example, for swift code let z = x ?? y , if x’s value is not nil then assign x’s value to z, otherwise it will assign y’s value to z. So let z = x ?? y can be treated as let z = x != nil ? x! : y. Below is a code example.
    // If set x to nil, then the variable z's value is 1 
    let x:Int? = nil
    
    //let x:Int? = 2
    
    let y:Int = 1
    
    let z = x ?? y
    
    print(z)
READ :   How To Use iOS UISwitch In Interface Builder And Programmatically In Swift Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.