Home > AI > Uncategorized

swift – 类型

//is 判断类型
    struct Movie {
        var name: String
    }
    struct Song {
        var singer: String
    }
    var movieCount = 1
    var songCount = 1
    func check(){
        let Library = Array<Any>()
        for item in Library {
            if item is Movie {
                movieCount += 1
            } else if item is Song {
                songCount += 1
            }
        }
    }
    
    //闭包
    func types(){
        var things = [Any]()
        things.append(0)
        things.append(0.8888)
        things.append(["Hotel" : 8]) //dictionary
        things.append((3, 5)) //元组
        things.append(Movie(name: "Maze Runner")) //类
        things.append({ (person: String) -> String in "Hello, \(person)" }) // 闭包
        
        for item in things {
            switch item {
            case 0 as Int:
                print("type is number")
            case let someInt as String:
                print("string value is \(someInt)")
            case is Double:
                print("I don't want to print")
            case is [String: Any]:
                print("pp")
            case let (x, y) as (Int, Int):
                print("location: \(x, y)")
            case let m as Movie:
                print("check whether is my favorite \(m.name)")
            case let funcs as (String) -> String:
                print(funcs("Mary"))
            default:
                print("other types")
            }
        }
    }

 

Related posts:

Leave a Reply