美文网首页
Swift基本语法速查

Swift基本语法速查

作者: herui201211 | 来源:发表于2019-01-01 20:24 被阅读9次

    基本使用

    //导入框架
    import Foundation
    
    //定义变量及常量
    let a : Int =10
    var i = 10
    
    //打印输出
    print(a)
    

    区间:

    //表示0~9的两种写法
    0..<10 
    0...9
    

    switch

    //支持 浮点、字符串、区间
    
    let score = 80
    
    switch score {
    case 0..<60:   print(不合格)
    case 60..<80:  print(合格)
    case 80...100: print(优秀)
    }
    

    循环

    for i in 0...10 {
      print(i)
    }
    for _ in 0...10 {
      print("hello swift")
    }
    
    var m = 0
    while m<10 {
      m += 1
    }
    repeat {
      m -= 1
    } while m>0
    

    字符串

    let name = "herui"
    let age = 18
    let info = name + age
    let infoDesc = "name is \(name), age is \(age)"
    
    let strLen = infoDesc.characters.count
    
    let min = 3
    let sec = 12
    let time = String(format:"%02d:%02d", min, sec)
    

    数组

    var arr = ["abc", "def"]
    arr.append("ghi")
    arr.remove(at: 0)
    arr[0] = "xxx"
    
    //数组遍历
    let count = arr.count
    for i in (0..<count) {
    }
    for item in arr {
    }
    for (index, item) in arr.enumerated() {
    }
    
    //数组合并
    let arr1 = ["a", "b"]
    let arr2 = ["c", "d"]
    let arr3 = arr1 + arr2
    

    字典

    var dict : [String : Any] = ["name" : "herui", "age" : 18]
    `var dict = [String : Any]()`
    dict["gender"] = "男" //可增加可修改
    dict.removeValue(forKey:"name")
    
    //字典遍历
    for key in dict.keys {
    }
    for value in dict.values {
    }
    for (key, value) in dict {
    }
    
    字典不可以直接相加合并,即使类型一致
    

    元组

    //数组
    var infoArray : [Any] = ["herui", 18] 
    //取出来的值类型是Any,需要as转换成明确的类型再进行操作
    infoArray[0] as! String
    infoArray[1] as! Int
    
    //字典
    var infoDict : ["String":Any] = ["name":"herui", "age":18]
    infoDict["name"] as! String
    infoDict["age"] as! Int
    
    //元组
    var infoTuple = (name:"herui", age:18)
    //无需转换(使用方便,无需类型转换)
    infoTuple.name
    infoTuple.age
    

    Optional可选类型

    //声明为可选类型,即表示它的值可能为nil
    
    var name : Optional<String> = nil
    var name : String? = nil
    name = "herui" //xcode自动包装为name = Optional("herui")
    
    //强制解包,如果值为nil时会崩溃
    name!
    //先判断,再解包
    if(name != nil){
      name!
    }
    //可选绑定(先判断是否为nil,再解包)推荐使用
    if let name = name {
      name //直接用
    }
    

    as类型转换

    var dict : ["String":Any] = ["name":"herui", "age":18]
    
    //用 as? 将Any转换为可选类型
    let name = dict["name"] as? String
    
    //用 as! 将Any转换为具体类型,如果为nil时程序崩溃
    let name = dict["name"] as! String
    
    //常见用法(从字典中取值)
    if let name = dict["name"] as? String {
      //name为具体类型
    }
    

    func函数

    func say() {
    }
    func say() -> String {
    }
    func say(str: String) -> String {
    }
    

    枚举类型

    enum MethodType : String {
        case GET = "GET"
        case POST = "POST"
    }
    MethodType.GET
    
    enum Direction {
        case east, west, north, south
    }
    Direction.east
    

    struct结构体

    //结构体中可以有方法及属性
    
    struct Location {
        var x : Float
        var y : Float
        
        //构造方法名固定为init
        //方法内部需要初始化所有的属性
        init(x: Float, y: Float) {//如果不写,这个方法会默认生成
            self.x = x
            self.y = y
        }
        init(str : String) {
            let arr = str.components(separatedBy: ",");
            self.x = Float(arr[0]) ?? 0
            self.y = Float(arr[1]) ?? 0
        }
        
        func desc() -> String {
            return "x is \(self.x), y is \(self.y)"
        }
    }
    
    var loc = Location(x: 0, y: 0)
    loc.x = 1.2
    
    let desc = loc.desc()
    print(desc)
    
    var loc2 = Location(str: "12,22")
    print(loc2)
    
    

    class类

    class Student {
    
        //存储属性
        var english : Double = 0.0
        var math : Double = 0.0
    
        //计算属性(只读)
        var ave : Double {
            return (english + math ) * 0.5;
        }
    
        //类属性
        static var desc : String = "Student"
        
        //属性监听
        var name : String = "" {
            willSet{
                print("willSet新值" + newValue)
                print("willSet未改变前的值" + name)
            }
            didSet{
                print("didSet改变前的旧值" + oldValue)
                print("didSet新值" + name)
            }
        }
        
        //默认构造函数
        init() { }
        //自定义构造函数
        init(dict: [String : Any]) {
            if let name = dict["name"] as? String {
                self.name = name
            }
            if let math = dict["math"] as? Double {
                self.math = math
            }
        }
        
        //析构函数
        deinit {
            print("deinit")
        }
    }
    
    
    let stu = Student()
    stu.english = 90
    stu.math = 60
    print(stu.ave)
    
    
    let stu2 = Student(dict: ["name": "herui", "math" : 66.0])
    print(stu2.name)
    print(stu2.math)
    
    var stu3 : Student? = Student()
    stu3 = nil
    
    

    protocol协议

    @objc protocol PersonDelegate : class {
        //必须实现
        func run()
        //可选实现需要加上optional,但是optional是OC部分的东西,所以加上@objc
        @objc optional func fly()
    }
    
    class Person : NSObject, PersonDelegate {
        //只有声明协议只能被class遵守时,delegate这里才能加上weak(防止循环引用)
        weak var delegate : PersonDelegate?
        
        func run() {
            print("run")
        }
    }
    

    闭包(block)

    (参数列表)->(返回值)
    
    /**
    为了模拟循环引用的问题,在vc里强引用了req,在req里强引用了completion闭包,而completion里又强引用了vc,导致循环引用。
    解决办法:在block回调里面用[weak self]打破了循环引用
    */
    class RequestManager {
        
        var url : String = ""
        var completion : ((_ result : String)->())?
        
        func request(completion : @escaping (_ result : String)->()){
            self.completion = completion
            
            DispatchQueue.global().async {
                print("请求数据中。。")
                DispatchQueue.main.async {
                    print("请求到数据")
                    completion("url: \(self.url)")
                }
            }
        }
    }
    
    class ViewController {
        var name  = "ViewController"
        var req : RequestManager?
        
        func test() {
            req = RequestManager();
            req?.url = "http://www.baidu.com";
    
     
            req?.request { [weak self] (str) in 
                print("name: \(self?.name ?? ""), result: \(str)")
            }
        }
        
        deinit {
            print("ViewController - deinit")
        }
    }
    
    var vc : ViewController? = ViewController()
    
    vc?.test()
    
    vc = nil
    
    
    

    懒加载

    class ViewController {
    
        lazy var info = ["herui", 18]
    
        lazy var button : UIButton = {
            let btn = UIButton()
            return btn
        }()
    }
    

    访问权限

    class Person {
        //默认,全包访问
        internal var name = "herui"
        //私有,仅本类
        private var age = 18
        //公开,跨包访问 UIView.frame
        open var height = 1.88
        //当前文件可访问
        fileprivate var weigth = 120
    
    }
    

    相关文章

      网友评论

          本文标题:Swift基本语法速查

          本文链接:https://www.haomeiwen.com/subject/hdwwlqtx.html