MG--Swift3.x进阶语法学习1

作者: Mg明明就是你 | 来源:发表于2017-03-14 16:08 被阅读90次
    • for循环的高级遍历

      • 一、遍历子控件而且指定是UILabel的控件才打印


      遍历子控件而且指定是UILabel的控件才打印
      • 二、使用Where关键字查找名字

    单个条件
    多个条件使用&&
    • 三、遍历中包含可选值

      • 通常写法:打印出来的是可选值
        通常写法
      • 优化写法:使用 case let name? 打印出来的不是可选值
        代替写法
    • nil的用法

    • 如果使用了可选类型,那么是非常危险的,通常就需要通过“!”强制解包,这就会导致程序崩溃(Crash)。Swift提供了一个??的操作符,如果可选类型为nil,会让它默认值

    • eg: 举个🌰
    let name: String? = "MG"
    let otherName  = name ?? "小明"
    print(otherName)
    // 打印出来的是  `MG`
    let name: String? = nil
    let otherName  = name ?? "小明"
    print(otherName)
    // 打印出来的是  `小明
    
    方法的返回值是可选值.png
    • 一般与关键字try连用

    - #####使用do  try catch
    

    - #####使用try? 可以简化成这样


    58D6345E-7927-492F-AF2C-C044796577CC.png

    - #####Optional binding(可选绑定)

    if let unwrappedAuthorName = authorName {
             print("Author is \(unwrappedAuthorName)")
    } else {
             print("No author.")
    }
    

    • Lazy Loading

      • eg:举个🌰
      • 普通

    class Person {
        let name: String
        init(name: String) {
            self.name = name
        }
        func reversedName() -> String {  // 字符串反转方法
            return "\(name.uppercased()) backwords is \(String(name.uppercased().characters.reversed()))"
        }
    }
    let person = Person(name: "ming Swift")
    print(person.reversedName())
    
    >  - #Lazy
    
    class Person {
        let name: String
        lazy var reversedName: String = self.getReversedName()
        init(name: String) {
            self.name = name
        }
        private func getReversedName() -> String { // 字符串反转方法
            return "\(name.uppercased()) backwords is \(String(name.uppercased().characters.reversed()))"
        }
    }
    let person = Person(name: "ming Swift")
    print(person.reversedName)
    

    打印出来的字符串是 “MING SWIFT backwords is TFIWS GNIM”


    • goto用法

      • 我们来看普通的方法
    var board = [[String]](repeating: [String](repeating: "",
                                               count: 10), count: 10)
    board[3][5] = "x"
    for (rowIndex, cols) in board.enumerated() {
          for (colIndex, col) in cols.enumerated() {
              if col == "x" {
                  print("Found the treasure at row \(rowIndex) col \(colIndex)!")
              }
          }
    }
    

    解释:虽然打印出来我们想要的结果,但是这段代码做了很多无用功。如果一开始搜索的找到的时候就使用break跳出循环。往下看看:

    var board = [[String]](repeating: [String](repeating: "",
                                               count: 10), count: 10)
    board[3][5] = "x"
    for (rowIndex, cols) in board.enumerated() {
          for (colIndex, col) in cols.enumerated() {
              if col == "x" {
                  print("Found the treasure at row \(rowIndex) col \(colIndex)!")
                  break
              }
          }
    }
    

    解释:然而,使用break也只是结束了当前的循环,so it would exit the for (colIndex, col) loop then continue running the for (rowIndex, cols) loop.(for (colIndex, col)这个循环直到跑完for (rowIndex, cols) 循环才会退出),这也浪费了一些时间。我们继续往下看更优化的代码:

    var board = [[String]](repeating: [String](repeating: "",
                                               count: 10), count: 10)
    board[3][5] = "x"
    rowLoop: for (rowIndex, cols) in board.enumerated() {
          for (colIndex, col) in cols.enumerated() {
              if col == "x" {
                  print("Found the treasure at row \(rowIndex) col \(colIndex)!")
                  break rowLoop
              }
          }
    }
    

    解释:标记你的循环。这会立即跳出循环,和结束后for (rowIndex, cols)循环——完美。

    • 再举个🌰

    -  未优化代码,层层嵌套
    
    if userRequestedPrint() {
            if documentSaved() {
              if userAuthenticated() {
                  if connectToNetwork() {
                      if uploadDocument("resignation.doc") {
                          if printDocument() {
                              print("Printed successfully!")
                          }
                      }
                   }
               }
             }
      }
    
    - 优化后的代码:使用Guard之后,层级会变得非常清晰,这样的代码可读性非常强
    
    printing: if userRequestedPrint() {
              guard documentSaved() else { break printing }
              guard userAuthenticated() else { break printing }
              guard connectToNetwork() else { break printing }
              guard uploadDocument("work.doc") else { break printing }
              guard printDocument() else { break printing }
              print("Printed successfully!")
    }
    



    • enum枚举和Struct结构体

      • eg:伦敦这个地方,有叫地理位置。有地铁🚇路线以及旅游景点。其中一个常量:地理位置,两个嵌套的枚举:地铁🚇路线以及旅游景点是一个枚举。

    enum London {  
            static let coordinates = (lat: 51.507222, long: -0.1275) // 地理位置(经纬度)
            enum SubwayLines {  // 地铁🚇路线
                case Bakerloo, Central, Circle, District, Elizabeth,HammersmithCity, Jubilee, Metropolitan, Northern, Piccadilly,
    Victoria, WaterlooCity
            }
            enum Places {   // 位置
                case BuckinghamPalace, CityHall, OldBailey, Piccadilly,StPaulsCathedral
            }
     }
    
    • 举个🌰 枚举

     enum R {
           enum Storyboards: String {
               case Main, Detail, Upgrade, Share, Help
           }
           enum Images: String {
               case Welcome, Home, About, Button
           } 
    }
    // 外界使用:现在流行的SnapKit,MJRefresh等度有自己的前缀开头也许就是这样搞的
    let home = R.Images.Home // 这样层级也很清晰
    
    • 举个🌰 枚举和结构体

    struct Deck {
            struct Card {
                enum Suit {
                    case Hearts, Diamonds, Clubs, Spades
                }
                var rank: Int
                var suit: Suit
            }
            var cards = [Card]()
    }
    // 外界使用:现在流行的SnapKit,MJRefresh等度有自己的前缀开头也许就是这样搞的
    let hearts = Deck.Card.Suit.Hearts // 这样层级也很清晰
    

    • 扫一扫,关注我

    扫一扫,关注我.jpg

    相关文章

      网友评论

        本文标题:MG--Swift3.x进阶语法学习1

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