swift 类型转换

  1. var movieCount = 0
  2. var songCount = 0
  3. for item in library {
  4. if item is Movie {
  5. movieCount += 1
  6. } else if item is Song {
  7. songCount += 1
  8. }
  9. }
  1. for item in library {
  2. if let movie = item as? Movie {
  3. print("Movie: (movie.name), dir. (movie.director)")
  4. } else if let song = item as? Song {
  5. print("Song: (song.name), by (song.artist)")
  6. }
  7. }

Type Casting for Any and AnyObject

Swift provides two special types for working with nonspecific types:

  • Any can represent an instance of any type at all, including function types.

  • AnyObject can represent an instance of any class type.

To discover the specific type of a constant or variable that is known only to be of type Any or AnyObject, you can use an is or as pattern in a switch statement’s cases. The example below iterates over the items in the things array and queries the type of each item with a switch statement. Several of the switch statement’s cases bind their matched value to a constant of the specified type to enable its value to be printed:

  1. for thing in things {
  2. switch thing {
  3. case 0 as Int:
  4. print("zero as an Int")
  5. case 0 as Double:
  6. print("zero as a Double")
  7. case let someInt as Int:
  8. print("an integer value of (someInt)")
  9. case let someDouble as Double where someDouble > 0:
  10. print("a positive double value of (someDouble)")
  11. case is Double:
  12. print("some other double value that I don't want to print")
  13. case let someString as String:
  14. print("a string value of "(someString)"")
  15. case let (x, y) as (Double, Double):
  16. print("an (x, y) point at (x), (y)")
  17. case let movie as Movie:
  18. print("a movie called (movie.name), dir. (movie.director)")
  19. case let stringConverter as (String) -> String:
  20. print(stringConverter("Michael"))
  21. default:
  22. print("something else")
  23. }
  24. }
  25. // zero as an Int
  26. // zero as a Double
  27. // an integer value of 42
  28. // a positive double value of 3.14159
  29. // a string value of "hello"
  30. // an (x, y) point at 3.0, 5.0
  31. // a movie called Ghostbusters, dir. Ivan Reitman
  32. // Hello, Michael
 
原文地址:https://www.cnblogs.com/feng9exe/p/9105980.html