Swift System Learning 29 Visualización de tipos y conversión de tipos Any y AnyObjec

//: Playground - noun: a place where people can play

import UIKit

/*
 * 本节主要内容:
 * 1.类型查看和类型转换
 * 2.Any和AnyObject
 */

/*
 * 1.类型查看运算符(Type Check Operator):  查看某个实例常量/变量是否是那个类型; 是否是该类子类的实例对象; 
    --> 关键词: is
 * 2.类型转换运算符(Type Casting Operator): 对某个实例对象进行类型换(as?返回该类型的可选型; as!进行强制类型转换)
    --> 关键词: as! 或者 as?
 */

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 libraries = [Movie(name:"血战钢锯岭", director:"梅尔--吉普森"), Movie(name:"我是传奇", director:"威尔--斯密斯"), Song(name:"Red", artist:"Taylor Swift"),Song(name:"Innocent", artist:"Avril Lavigne"), Song(name:"Love Story", artist:"Taylor Swift")]
// 判断几首歌, 几部电影 
var movieCount = 0
var songCount  = 0
for item in libraries {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}
print("The count of movie are \(movieCount) and song are \(songCount)")

// 需求: 分别打印电影和歌曲的信息
for item in libraries {
    // movie是Movie?可选型
    if let movie = item as? Movie {
        print("Movie's name is \(movie.name) and director is \(movie.director)")
    } else if let song = item as? Song {
        print("Song's name is \(song.name) and artist is \(song.artist)")
    }
}

/*
 * 1.AnyObject: 描述任意类类型(Class Type)的实例对象
 * 2.Any: 描述任意类型(类/结构体/枚举/函数类型...)的实例对象
 * 3.适用场景: JSON解析
    var dictionary: [String: Any] = [:]
 */
let newLibrary: [Any] = [Movie(name:"血战钢锯岭", director:"梅尔--吉普森"), Movie(name:"我是传奇", director:"威尔--斯密斯")]
// (NSHTTPURLResponse *)response
for object in newLibrary {
    // as!: 只要能保证绝对可以强制转换成功, 最好选择as!, 因为as?需要解包
    let movie = object as! Movie
}

// 声明一个数组变量, 元素的类型Any
var array: [Any] = []
array.append(0)
array.append(0.0)
array.append(42)
array.append(3.1415926)
array.append("hello")
array.append((3.0, 5.5))
array.append(Movie(name:"血战钢锯岭", director:"梅尔--吉普森"))
array.append({(name: String) -> String in "Hello to \(name)"})

for item in array {
    switch item {
    case 0 as Int:
        print("Zero is Int type.")
    case 0 as Double:
        print("Zero is Double type.")
    case let someInt as Int:
        print("an integer value is \(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("a positive double type of \(someDouble)")
    case is Double:
        print("Some other double value and cannot print it.")
    case let (x, y) as (Double, Double):
        print("an (x, y) point as \(x), \(y)")
    case let movie as Movie:
        print("Movie's name is \(movie.name) and director is \(movie.director)")
    case is String:
        print("This is the simple String.")
        // 判定函数是否是下面描述的类型, 如果是, 执行闭包
    case let returnStringFuntion as (String) -> String:
        print(returnStringFuntion("Michael"))
    default:
        print("Something else......")
    }
}





Supongo que te gusta

Origin blog.csdn.net/clarence20170301/article/details/59108980
Recomendado
Clasificación