问号操作符号

//
//  ViewController.swift
//  可选项的判断
//
//  Created by 思 彭 on 16/9/16.
//  Copyright © 2016年 思 彭. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        demo1(x: 20, y: nil)
    }

    func demo(x: Int?,y: Int?) {
        // 1. 强行解包有风险
        print(x! + y!)
        // 2.使用if判断  直接使用if,使代码看起来很丑陋
        if x != nil && y != nil {
            print(x! + y!)
        }
        else{
            print("x或者y为nil")
        }
    }
    
    //MARK:
    func demo1(x: Int?,y: Int?) {
    
        // 记得括号括起来
        print((x ?? 0) + (y ?? 0))  //20
        
        let name: String? = nil
        print((name ?? "") + ("你好"))  //你好
        // 注意: ??优先级低
        print(name ?? "" + "思思") // 思思
    }


}
原文地址:https://www.cnblogs.com/pengsi/p/5877143.html