码迷,mamicode.com
首页 > 编程语言 > 详细

Swift4 类型转换,例子代码

时间:2018-04-21 19:30:58      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:sel   AMM   cas   media   self   res   HERE   awk   content   

类型转换

苹果官方指南 Type Casting

苹果官方指南翻译 类型转换

类型转换可判断实例类型,也可将实例在雷层次中视为父类或子类的实例。

操作符为 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]

类型检查

类型检查操作符 is 来检查一个实例是否属于一个特定的子类。是返回 true,否则返回 false。

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! 将它向下类型转换至其子类类型或父类类型。

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 为不确定的类型提供了两种特殊的类型别名:

  • AnyObject 可以表示任何类类型的实例。
  • Any 可以表示任何类型,包括函数类型。
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
let optionalNumber: Int? = 3
things.append(optionalNumber)        // Warning
things.append(optionalNumber as Any) // No warning

Swift4 类型转换,例子代码

标签:sel   AMM   cas   media   self   res   HERE   awk   content   

原文地址:https://www.cnblogs.com/ccjoy/p/8902275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!