1. 程式人生 > >Swift從入門到精通第十五篇 - 型別轉換 初識

Swift從入門到精通第十五篇 - 型別轉換 初識

型別轉換(學習筆記)

環境Xcode 11.0 beta4 swift 5.1

  • 型別轉換
    • 型別轉換是檢查例項型別的一種方法,或者檢查來自類層級不同的父類或子類一個例項,用 isas 操作符
  • 為型別轉換定義層級結構
    • 示例

      class MediaItem {
          var name: String
          init(name: String) {
              self.name = name
          }
      }
      class Movie: MediaItem {
          var director: String
          init(name: String, director: String) {
              self.director = director
              super.init(name: name)
          }
      }
      // 
      class Song: MediaItem {
          var artist: String
          init(name: String, artist: String) {
              self.artist = artist
              super.init(name: name)
          }
      }
      let library = [
          Movie(name: "Casablanca", director: "Michael Curtiz"),
          Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
          Movie(name: "Citizen Kane", director: "Orson Welles"),
          Song(name: "The One And Only", artist: "Chesney Hawkes"),
          Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
      ]
      // "library" 型別編譯器自動推導為: [MediaItem]
  • 型別檢查
    • 示例

      var movieCount = 0
      var songCount = 0
      // 
      for item in library {
          if item is Movie {
              movieCount += 1
          } else if item is Song {
              songCount += 1
          }
      }
      // 
      print("Media library contains \(movieCount) movies and \(songCount) songs")
      // Prints "Media library contains 2 movies and 3 songs"
  • 型別向下轉換
    • 可以用 as?as! 實現型別轉換,型別轉換有可能失敗,as?返回一個可選型別, as!嘗試型別轉換且強制解包,如果型別轉換不不正確,會觸發執行時錯誤

      for item in library {
          if let movie = item as? Movie {
              print("Movie: \(movie.name), dir. \(movie.director)")
          } else if let song = item as? Song {
              print("Song: \(song.name), by \(song.artist)")
          }
      }
      //
      // Movie: Casablanca, dir. Michael Curtiz
      // Song: Blue Suede Shoes, by Elvis Presley
      // Movie: Citizen Kane, dir. Orson Welles
      // Song: The One And Only, by Chesney Hawkes
      // Song: Never Gonna Give You Up, by Rick Astley
  • Any AnyObject 型別轉換
    • Swift 為非指定型別提供了兩種特殊型別
      • Any 可以代表例項型別,包括函式
      • AnyObject 可以代表任何類型別的例項
        swift var things = [Any]() // things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({ (name: String) -> String in "Hello, \(name)" }) for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of \(someDouble)") case is Double: print("some other double value that I don't want to print") case let someString as String: print("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): print("an (x, y) point at \(x), \(y)") case let movie as Movie: print("a movie called \(movie.name), dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("something else") } } // // zero as an Int // zero as a Double // an integer value of 42 // a positive double value of 3.14159 // a string value of "hello" // an (x, y) point at 3.0, 5.0 // a movie called Ghostbusters, dir. Ivan Reitman // Hello, Michael
  • 注意
    • 如果你想用可選值作為 Any 值,那麼要用 as 操作符顯示的將型別轉換為 Any

      let optionalNumber: Int? = 3
      things.append(optionalNumber)        // Warning
      things.append(optionalNumber as Any) // No warning