Swift入门

从The Swift Programming Language中总结出来的,拷贝到Xcode6中即可运行。
import Foundation

println("Hello, World!")

//赋值
let myVar:Float = 4
println(myVar)


//值的转换没有隐式转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
println(widthLabel)

//另一种将值装换为String的方式\()
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
let fruitPriceSumary = "This is String \(0.8), not float"
println(appleSummary + " " + fruitSummary + " " + fruitPriceSumary)

//使用[]创建数组或者字典,并访问
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
println(shoppingList[0..4])

var occupations = [
  "Malcolm": "Captain",
  "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
println(occupations["Malcolm"])
println(occupations["Kaylee"])
println(occupations["Jayne"])

//空数字或者空字典
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

//for语句
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
  if score > 50 {
    teamScore += 3
  } else {
    teamScore += 1
  }
}
println(teamScore)

//if语句
var optionalString: String? = "Hello"//类型后面?表示这个值是可选的
optionalString == nil//可以是nil或者具体值

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
  greeting = "Hello, \(name)"
} else {
  greeting = "optionalName is NIL"
}
println(greeting)

//switch语句,default语句不可以少,也不需要在每个语句后面写break
let vegetable = "red pepper"
switch vegetable {
case "celery":
  let vegetableComment = "Add some raisins and make ants on a log."
  println(vegetableComment)
case "cucumber", "watercress":
  let vegetableComment = "That would make a good tea sandwich."
  println(vegetableComment)
case let x where x.hasSuffix("pepper"):
  let vegetableComment = "Is it a spicy \(x)?"
  println(vegetableComment)
default:
  let vegetableComment = "Everything tastes good in soup."
  println(vegetableComment)
}


//for-in遍历
let interestingNumbers = [
  "Prime": [2, 3, 5, 7, 11, 13],
  "Fibonacci": [1, 1, 2, 3, 5, 8],
  "Square": [1, 4, 9, 16, 25],
  "sp": [1, 4, 9, 25],//为什么取出来的是S,不是Square????
]
var largest = 0
var type = "";
for (kinds, numbers) in interestingNumbers {
  for number in numbers {
    if number > largest {
      largest = number
      type = kinds
    }
  }
  println("\(kinds) : \(numbers)") //遍历
}
println("\(type) : \(largest)") //只显示最大

//while
var n = 2
while n < 100 {
  n = n * 2
}
println(n)

var m = 2
do {
  m = m * 2
} while m < 100
println(m)

//for的上下界
//使用..创建的范围不包含上界,如果想包含的话需要使用...
var firstForLoop = 0
var secondForLoop = 0
for i in 0..3 {
  firstForLoop += i
}
for i in 0...3 {
  secondForLoop += i
}
println(firstForLoop)
println(secondForLoop)

//函数
func greet(name: String, day: String) -> String {
  return "Hello \(name), today is \(day)."
}
println(greet("Bob", "Tuesday"))

//一个元组来返回多个值。
func getGasPrices() -> (Double, Double, Double) {
  return (3.59, 3.69, 3.79)
}
println(getGasPrices())

//函数的参数数量是可变的,用一个数组来获取它们:
func sumOf(numbers: Int...) -> Int {
  var sum = 0
  for number in numbers {
    sum += number
  }
  return sum
}
println(sumOf(42, 597, 12))

//函数的嵌套
func returnFifteen() -> Int {
  var y = 10
  func add() {
    y += 5
  }
  add()
  return y
}
println(returnFifteen())

//函数可以作为另一个函数的返回值
func makeIncrementer() -> (Int -> Int) {
  func addOne(number: Int) -> Int {
    return 1 + number
  }
  return addOne
}
var increment = makeIncrementer()
println(increment(7))

//函数也可以当做参数传入另一个函数。
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
  for item in list {
    if condition(item) {
      return true
    }
  }
  return false
}
func lessThanTen(number: Int) -> Bool {
  return number < 10
}
var numbers = [20, 19, 7, 12]
println(hasAnyMatches(numbers, lessThanTen))

//函数实际上是一种特殊的闭包,你可以使用{}来创建一个匿名闭包。使用in来分割参数并返回类型。
numbers.map({
  (number: Int) -> Int in
  let result = 3 * number
  println(result)
  return result
})

//如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型和返回值。单个语句闭包会把它语句的值当做结果返回。
//你可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用。当一个闭包作为最后一个参数传给一个函数的时候,它可以直接跟在括号后面。
println(sort([1, 5, 3, 12, 2]) { $0 > $1 })

//类
class Shape {
  var numberOfSides = 0
  func simpleDescription() -> String {
    return "A shape with \(numberOfSides) sides."
  }
}
//上面这个类的类实例
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
println(shapeDescription)

//带构造器的类
class NamedShape {
  var numberOfSides: Int = 0
  var name: String
  
  init(name: String) {
    self.name = name
  }
  
  func simpleDescription() -> String {
    return "A shape with \(numberOfSides) sides."
  }
}

//子类
class Square: NamedShape {
  var sideLength: Double
  
  init(sideLength: Double, name: String) {
    self.sideLength = sideLength
    super.init(name: name)
    numberOfSides = 4
  }
  
  func area() ->  Double {
    return sideLength * sideLength
  }
  
  override func simpleDescription() -> String { //重载必须要有overload否则会报错
    return "A square with sides of length \(sideLength)."
  }
}
let test = Square(sideLength: 5.2, name: "my test square")
println(test.area())
println(test.simpleDescription())

//属性的getter和setter
class EquilateralTriangle: NamedShape {
  var sideLength: Double = 0.0
  
  init(sideLength: Double, name: String) {
    self.sideLength = sideLength
    super.init(name: name)
    numberOfSides = 3
  }
  
  var perimeter: Double {
  get {
    return 3.0 * sideLength
  }
  set {
    sideLength = newValue / 3.0
  }
  }
  
  override func simpleDescription() -> String {
    return "An equilateral triagle with sides of length \(sideLength)."
  }
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
println(triangle.perimeter)
triangle.perimeter = 9.9
println(triangle.sideLength)

//如果你不需要计算属性但是需要在设置一个新值之前运行一些代码,使用willSet和didSet。
class TriangleAndSquare {
  var triangle: EquilateralTriangle {
  willSet {
    square.sideLength = newValue.sideLength
  }
  }
  var square: Square {
  willSet {
    triangle.sideLength = newValue.sideLength
  }
  }
  init(size: Double, name: String) {
    square = Square(sideLength: size, name: name)
    triangle = EquilateralTriangle(sideLength: size, name: name)
  }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
println(triangleAndSquare.square.sideLength)
println(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
println(triangleAndSquare.triangle.sideLength)

//类中的方法和一般的函数有一个重要的区别,函数的参数名只在函数内部使用,但是方法的参数名需要在调用的时候显式说明(除了第一个参数)。默认情况下,方法的参数名和它在方法内部的名字一样,不过你也可以定义第二个名字,这个名字被用在方法内部。
class Counter {
  var count: Int = 0
  func incrementBy(amount: Int, numberOfTimes times: Int) {
    count += amount * times
    println(count)
  }
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)

//枚举
enum Rank: Int {
  case Ace = 1 //枚举原始值的类型是Int,所以你只需要设置第一个原始值。剩下的原始值会按照顺序赋值。你也可以使用字符串或者浮点数作为枚举的原始值。
  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
println(ace)
let aceRawValue = ace.toRaw()
println(aceRawValue)

//使用toRaw和fromRaw函数来在原始值和枚举值之间进行转换。
if let convertedRank = Rank.fromRaw(3) {
  let threeDescription = convertedRank.simpleDescription()
  println(threeDescription)
}

//枚举的成员值是实际值,并不是原始值的另一种表达方法。实际上,如果原始值没有意义,你不需要设置。
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()
println(hearts)
println(heartsDescription)

//结构体--结构体是传值,类是传引用
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()
println(threeOfSpadesDescription)

//接口
protocol ExampleProtocol {
  var simpleDescription: String { get }
  mutating func adjust()
}
//类、枚举和结构体都可以实现接口。
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

//扩展
//可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。
extension Int: ExampleProtocol {
  var simpleDescription: String {
  return "The number \(self)"
  }
  mutating func adjust() {
    self += 42
  }
}
println(7.simpleDescription)

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

//泛型
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
  var result = ItemType[]()
  for i in 0..times {
    result += item
  }
  return result
}
println(repeat("knock", 4))
//泛型类、枚举和结构体。
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 {
  //可以忽略where,只在冒号后面写接口或者类名。<T: Equatable>和<T where T: Equatable>是等价的。
  for lhsItem in lhs {
    for rhsItem in rhs {
      if lhsItem == rhsItem {
        return true
      }
    }
  }
  return false
}
println(anyCommonElements([1, 2, 3], [3]))

猜你喜欢

转载自windypig.iteye.com/blog/2078443