swift里 as、as!、as?区别 T.Type与动态类型

as 

1、编译器进行类型转换合法性检查;静态

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: shoppingList[indexPath.section], for: indexPath as IndexPath)

 let k = cell as IndexPath

Cannot convert value of type 'UICollectionViewCell' to type 'IndexPath' in coercion

2、配合switch:类型探测

as!as?

类型动态转化;

任意类型转化为特定类型;类型体系检查。

类型作为函数参量时,属于动态类型;

类型系统和编译器密切相关。

使用类型进行实例初始化时,编译器要求类型限定必须是静态的;(相对于函数调用)。

所以作为类型传入的类型参数,用于给实例初始化时,必须做限定。

(type as! HMLoginModel.Type).init()

extension ObservableType where E == Response {

    public func mapModel<T: HandyJSON>(_ type: T.Type) -> Observable<T> {

        return flatMap { response -> Observable<T> in

            (type as! HMLoginModel.Type).init()

            return Observable.just(response.mapModel(T.self))

        }

    }

}

猜你喜欢

转载自www.cnblogs.com/feng9exe/p/9179463.html