zoukankan      html  css  js  c++  java
  • 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
     
  • 相关阅读:
    Windows下使用CMake编译SuiteSparse成VS工程
    【设计模式
    【设计模式
    vue过滤和复杂过滤
    el-tooltip 自定义样式
    el-table加表单验证
    使用Go env命令设置Go的环境
    面试官:GET 和 POST 两种基本请求方法有什么区别?
    解决 Vue 重复点击相同路由报错的问题
    利用promise和装饰器封装一个缓存api请求的装饰器工具
  • 原文地址:https://www.cnblogs.com/feng9exe/p/9105980.html
Copyright © 2011-2022 走看看