职群教育 | IOS开发 Swift语言入门(六):接口、扩展和泛型



注:本文参考苹果官方文档,讲解swift2.0语言的入门知识,使用IDE为Xcode7.2

  • 接口、扩展
使用protocol来声明一个接口。
protocol ExampleProtocol { 
    var simpleDescription: String { get } 
    mutating func adjust() //mutating关键词,允许内部方法修改内部值。因为是接口,所以不用编写方法体
} 

类、枚举和结构体都可以实现接口。
class SimpleClass: ExampleProtocol { 
    var simpleDescription: String = "A very simple class." 
    var anotherProperty: Int = 69105 
    func adjust() { 
        simpleDescription += "  Now 100% adjusted." 
    } 
} 
var a = SimpleClass() 
a.adjust() 
let aDescription = a.simpleDescription 
  
struct SimpleStructure: ExampleProtocol { 
    var simpleDescription: String = "A simple structure" 
    mutating func adjust() { 
        simpleDescription += " (adjusted)" 
    } 
} 
var b = SimpleStructure() 
b.adjust() 
let bDescription = b.simpleDescription 

大家注意下,类的方法不用再声明关键词mutating,而结构体是需要mutating的

练习:写一个实现这个接口的枚举。

 
使用 extension 来为现有的类扩展功能,比如添加一个计算属性的方法。
你可以使用扩展来给任意类型添加接口协议,甚至是从外部库或框架中导入的类型。 
extension Int: ExampleProtocol { //扩展Int类
    var simpleDescription: String { //扩展一个属性
    return "The number \(self)" 
    } 
    mutating func adjust() { //扩展一个方法
        self += 42 
    } 
} 
 
7.simpleDescription 

练习 :给Double类型写一个扩展,添加absoluteValue功能。

大家可以像使用其他命名类型一样使用接口名。如创建一个有不同类型但是都实现一个接口的对象集合。
当你处理类型是接口的值时,接口外定义的方法不可用。
let protocolValue: ExampleProtocol = a 
protocolValue.simpleDescription 
// protocolValue.anotherProperty  // Uncomment to see the error 

即使protocolValue变量运行时的类型是simpleClass,编译器会把它的类型当做ExampleProtocol。这表示你不能调用类在它实现的接口之外实现的方法或者属性。
 
  • 泛型

在尖括号里写一个名字来创建一个泛型函数或类型。  
enum ItemType {
    case item
}
func arrays<ItemType>(item: ItemType, times: Int)->[ItemType]{
    
    var result = [ItemType]()
    for _ in 1...times {
        result.append(item)
    }
    return result
}
arrays(ItemType.item, times:4)

也可以创建泛型的类、枚举和结构体。如下,泛型的枚举
// Reimplement the Swift standard library's optional type 
enum OptionalValue<T> { 
    case None 
    case Some(T) 
} 
var possibleInteger: OptionalValue<Int> = .None 
possibleInteger = .Some(100) 

在类型名后面使用where来指定一个需求列表。
例如,要限定实现一个协议的类型,需要限定两个类型要相同,
或者限定一个类必须有一个特定的父类。
以下是官方的样例代码,有兴趣的可以把他吃透
func anyCommonElements <T, 
U where T: Sequence, U: Sequence, 
T.GeneratorType.Element: Equatable, 
T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { 
    for lhsItem in lhs { 
        for rhsItem in rhs { 
            if lhsItem == rhsItem { 
                return true 
            } 
        } 
    } 
    return false 
} 
anyCommonElements([1, 2, 3], [3]) 

练习 :修改anyCommonElements函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。
 
为了简单形象,你其实可以忽略where,
只在冒号后面写接口或者类名。<T: Equatable>和<T where T: Equatable>是等价的。


P.S.这是swift入门系列的终结篇,春节后继续撰写新的教程,
大家可以自己设计一些小的实战,把这些基础编程都应用上去,加深理解和吸收

祝大家春节快乐,猴年吉祥



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值