• Swift开发第九篇——Any和AnyObject&typealias和泛型接口


    本篇分为两部分:

    一、Swift中的Any和AnyObject

    二、Swift中的typealias和泛型接口


    一、Swift中的Any和AnyObject

      在 Swift 中,AnyObject 可以代表任何 class 类型的实例,Any 可以表示任意类型,包括方法(func)类型,相当于 OC 中的 id。因为 id 可以为空,所以 AnyObject 也是Optional类型的。

    验证 Any 和 AnyObject 的特性:

    import UIKit
    let swiftInt: Int = 1
    let swiftString: String = "miao"
    var array: [AnyObject] = []
    array.append(swiftInt)
    array.append(swiftString)

     数组 array 中的情况:

      我们这里生命了一个 Int 和一个 String 类型的常量,按理说他们只能被 Any 代表,而不能被 AnyObject 代码,但是编译运行可以通过。这是因为在 Swift 和 Cocoa 中的这几个对应的类型是可以进行自动转换的。如果对性能要求高还是尽量使用原生的类型。在变成过程中还是尽量明确数据类型,少用 AnyObject。

    二、Swift中的typealias和泛型接口

    在 Swift 中是没有泛型接口的,但是使用 typealias 可以在接口里定义一个必须实现的别名。

    class Person<T> {}
    typealias WorkId = String
    typealias Worker = Person<WorkId>
    
    protocol GeneratorType {
        typealias Element
        mutating func next() -> Self.Element?
    }
    protocol SequenceType {
        typealias Generator : GeneratorType
        func generate() -> Self.Generator
    }

    正常情况下,我们的代码是这样的:

    func distanceBetweenPoint(point: CGPoint, toPoint: CGPoint) -> Double {
        let dx = Double(toPoint.x - point.x)
        let dy = Double(toPoint.y - point.y)
        return sqrt(dx * dx + dy * dy)
    }
    let origin: CGPoint = CGPoint(x: 0, y: 0)
    let point: CGPoint = CGPoint(x: 1, y: 1)
    let distance: Double =  distanceBetweenPoint(origin, toPoint: point)

    利用 typealias 之后将会大大提高我们代码的阅读性:

    typealias Location = CGPoint
    typealias Distance = Double
    func distanceBetweenPoint(location: Location,
        toLocation: Location) -> Distance {
            let dx = Distance(location.x - toLocation.x)
            let dy = Distance(location.y - toLocation.y)
            return sqrt(dx * dx + dy * dy)
    }
    let originP: Location = Location(x: 0, y: 0)
    let pointP: Location = Location(x: 1, y: 1)
    let distanceD: Distance =  distanceBetweenPoint(origin, toLocation: point)
  • 相关阅读:
    MySQL server has gone away 问题的解决方法
    MySQL批量SQL插入性能优化
    mysql中int、bigint、smallint 和 tinyint的区别详细介绍
    Mac OS使用ll、la、l等ls的别名命令
    Github上的PHP资源汇总大全
    svn代码版本管理总结
    mysql information_schema介绍
    redis 五种数据结构详解(string,list,set,zset,hash)
    git 换行符LF与CRLF转换问题
    php 利用activeMq+stomp实现消息队列
  • 原文地址:https://www.cnblogs.com/Jepson1218/p/5294296.html
Copyright © 2020-2023  润新知