Swift中文教程3

来源:互联网 发布:dcs控制系统与cms 编辑:程序博客网 时间:2024/05/16 11:34

调用方法

Swift中,函数的参数名称只能在函数内部使用,但方法的参数名称除了在内部使用外还可以在外部使用(第一个参数除外),例如:

  • class Counter {
  •     var count: Int = 0
  •     func incrementBy(amount: Int, numberOfTimes times: Int) {
  •         count += amount * times
  •     }
  • }
  • var counter = Counter()
  • counter.incrementBy(2, numberOfTimes: 7)

注意Swift支持为方法参数取别名:在上面的代码里,numberOfTimes面向外部,times面向内部。

?的另一种用途

使用可空值时,?可以出现在方法、属性或下标前面。如果?前的值为nil,那么?后面的表达式会被忽略,而原表达式直接返回nil,例如:

  • let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional
  • square")
  • let sideLength = optionalSquare?.sideLength

当optionalSquare为nil时,sideLength属性调用会被忽略。

枚举和结构

枚举

使用enum创建枚举——注意Swift的枚举可以关联方法:

  • enum Rank: Int {
  •     case Ace = 1
  •     case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
  •     case Jack, Queen, King
  •         func simpleDescription() -> String {
  •         switch self {
  •             case .Ace:
  •                 return "ace"
  •             case .Jack:
  •                 return "jack"
  •             case .Queen:
  •                 return "queen"
  •             case .King:
  •                 return "king"
  •             default:
  •                 return String(self.toRaw())
  •         }
  •     }
  • }
  • let ace = Rank.Ace
  • let aceRawValue = ace.toRaw()

 

使用toRaw和fromRaw在原始(raw)数值和枚举值之间进行转换:

  • if let convertedRank = Rank.fromRaw(3) {
  • let threeDescription = convertedRank.simpleDescription()
  • }

注意枚举中的成员值(member value)是实际的值(actual value),和原始值(raw value)没有必然关联。

一些情况下枚举不存在有意义的原始值,这时可以直接忽略原始值:

  • enum Suit {
  •     case Spades, Hearts, Diamonds, Clubs
  •         func simpleDescription() -> String {
  •         switch self {
  •             case .Spades:
  •                 return "spades"
  •             case .Hearts:
  •                 return "hearts"
  •             case .Diamonds:
  •                 return "diamonds"
  •             case .Clubs:
  •                 return "clubs"
  •         }
  •     }
  • }
  • let hearts = Suit.Hearts
  • let heartsDescription = hearts.simpleDescription()

除了可以关联方法,枚举还支持在其成员上关联值,同一枚举的不同成员可以有不同的关联的值:

  • enum ServerResponse {
  •     case Result(String, String)
  •     case Error(String)
  • }
  • let success = ServerResponse.Result("6:00 am", "8:09 pm")
  • let failure = ServerResponse.Error("Out of cheese.")
  • switch success {
  •     case let .Result(sunrise, sunset):
  •         let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
  •     case let .Error(error):
  •         let serverResponse = "Failure... \(error)"
  • }

结构

Swift使用struct关键字创建结构。结构支持构造器和方法这些类的特性。结构和类的最大区别在于:结构的实例按值传递(passed by value),而类的实例按引用传递(passed by reference)。

  • struct Card {
  •     var rank: Rank
  •     var suit: Suit
  •     func simpleDescription() -> String {
  •         return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
  •     }
  • }
  • let threeOfSpades = Card(rank: .Three, suit: .Spades)
  • let threeOfSpadesDescription = threeOfSpades.simpleDescription()

协议(protocol)和扩展(extension) 协议

Swift使用protocol定义协议:

  • protocol ExampleProtocol {
  •     var simpleDescription: String { get }
  •     mutating func adjust()
  • }

类型、枚举和结构都可以实现(adopt)协议:

  • 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

扩展

扩展用于在已有的类型上增加新的功能(比如新的方法或属性),Swift使用extension声明扩展:

  • extension Int: ExampleProtocol {
  •     var simpleDescription: String {
  •         return "The number \(self)"
  •     }
  •     mutating func adjust() {
  •         self += 42
  •     }
  • }
  • 7.simpleDescription

泛型(generics)

Swift使用<>来声明泛型函数或泛型类型:

  • func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
  •     var result = ItemType[]()
  •     for i in 0..times {
  •         result += item
  •     }
  •     return result
  • }
  • repeat("knock", 4)

 

Swift也支持在类、枚举和结构中使用泛型:

  • // Reimplement the Swift standard library's optional type
  • enum OptionalValue<T> {
  •     case None
  •     case Some(T)
  • }
  • var possibleInteger: OptionalValue<Int> = .None
  • possibleInteger = .Some(100)

 

有时需要对泛型做一些需求(requirements),比如需求某个泛型类型实现某个接口或继承自某个特定类型、两个泛型类型属于同一个类型等等,Swift通过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])
0 0
原创粉丝点击