首页 iOS.& Swift Books uikit学徒

21
快速评论 由Matthijs Hollemans撰写& Fahim Farook

你取得了很大进展!你’ve learnt the basics of Swift programming and created two applications from scratch. You are on the threshold of creating your next app.

但是,一个良好的建筑需要一个良好的基础。并且为了加强您的SWIFT知识的基础,您首先需要一些额外的理论。了解SWIFT和面向对象的编程仍有更多更多。

在以前的章节中,我已经证明了Swift Profrafy的公平束缚,纽扣一切。以前,如果你的矿石或更少的人遵循我们所做的事情,那就足够了,以填补理论上的空白。休息,让我们搅拌一下我们迄今为止所谈论的东西。

在本章中,您将介绍以下内容:

  • 变量,常量和类型: 变量和常量之间的区别,以及类型是什么。
  • 方法和功能: 什么是方法和功能 - 它们是同一件事吗?
  • 做出决定: 对各种编程构造的说明,可用于节目的决策过程。
  • 循环: 如何循环通过项目列表?
  • 对象: 所有你想知道对象 - 他们是什么,他们的组件零件,如何使用它们,以及如何滥用它们。
  • 协议: 关于协议的细节,具体化细节。

变量,常数和类型

变量和类型

A 多变的 是特定类型的临时容器:

var count: Int
var shouldRemind: Bool
var text: String
var list: [ChecklistItem]
var i = 10
var f: Float
f = i         // error
f = Float(i)  // OK
var i = 10              // Int
var d = 3.14            // Double
var b = true            // Bool
var s = "Hello, world"  // String
var f: Float = 3.14
var i: Double = 10
var i = 10.0
var item: ChecklistItem
item = ChecklistItem()
var item = ChecklistItem()
var item = ChecklistItem(text: "Charge my iPhone", checked: false)
class MyObject {
  var count = 0      // an instance variable

  func myMethod() {
    var temp: Int    // a local variable
    temp = count     // OK to use the instance variable here
  }

  // the local variable “temp” doesn’t exist outside the method
}
class MyObject {
  var count = 7      // an instance variable

  func myMethod() {
    var count = 42   // local variable “hides” instance variable
    print(count)     // prints 42
  }
}
  func myMethod() {
    var count = 42
    print(self.count)   // prints 7
  }

常数

变量不是可以保存值的唯一代码元素。变量是允许值的容器 改变 在运行应用程序的过程中。

let pi = 3.141592
let difference = abs(targetValue - currentValue)
let message = "You scored \(points) points"
let image = UIImage(named: "SayCheese")

值类型与引用类型

使用基本值(如整数和字符串) - 哪个 价值类型 — a constant created with let cannot be changed once it has been given a value:

let pi = 3.141592
pi = 3                // not allowed
let item = ChecklistItem()
item.text = "Do the laundry"
item.checked = false
item.dueDate = yesterday
let anotherItem = ChecklistItem()
item = anotherItem   // cannot change the reference

收藏品

变量仅存储单个值。要跟踪多个对象,可以使用a 收藏 object. Naturally, I’m talking about arrays (Array) and dictionaries (Dictionary), both of which you’ve seen previously.

// An array of ChecklistItem objects:
var items: Array<ChecklistItem>

// Or, using shorthand notation:
var items: [ChecklistItem]

// Making an instance of the array:
items = [ChecklistItem]()

// Accessing an object from the array:
let item = items[3]
// A dictionary that stores (String, Int) pairs, for example a
// list of people’s names and their ages:
var ages: Dictionary<String, Int>

// Or, using shorthand notation:
var ages: [String: Int]

// Making an instance of the dictionary:
ages = [String: Int]()

// Accessing an object from the dictionary:
var age = dict["Jony Ive"]

仿制

Array and Dictionary are known as 仿制,这意味着它们与您想要存储在这些集合中的东西类型。

var items: Array  // error: should be Array<TypeName>
var items: []     // error: should be [TypeName]

术语

有时它有一个可以没有值的变量很有用,在这种情况下,您需要将其声明为一个 选修的:

var checklistToEdit: Checklist?
if let checklist = checklistToEdit {
  // “checklist” now contains the real object
} else {
  // the optional was nil
}
if let age = dict["Jony Ive"] {
  // use the value of age
}
var age = dict["Jony Ive"]!
navigationController!.delegate = self
navigationController?.delegate = self
if navigationController != nil {
  navigationController!.delegate = self
}
var dataModel: DataModel!

方法和功能

您已经了解到,所有应用程序的基本构建块,都具有数据和功能。实例变量和常量提供数据, 方法 提供功能。

let result = performUselessCalculation(314)
print(result)

. . .

func performUselessCalculation(_ a: Int) -> Int {
  var b = Int(arc4random_uniform(100))
  var c = a / 2
  return (a + b) * c
}
// Method with no parameters, no return a value.
override func viewDidLoad()

// Method with one parameter, slider. No return a value.
// The keyword @IBAction means that this method can be connected
// to a control in Interface Builder.
@IBAction func sliderMoved(_ slider: UISlider)

// Method with no parameters, returns an Int value.
func countUncheckedItems() -> Int

// Method with two parameters, cell and item, no return value.
// Note that the first parameter has an extra label, for, 
// and the second parameter has an extra label, with.
func configureCheckmarkFor(
  for cell: UITableViewCell, 
  with item: ChecklistItem)

// Method with two parameters, tableView and section. 
// Returns an Int. The _ means the first parameter does not 
// have an external label.
override func tableView(
  _ tableView: UITableView, 
  numberOfRowsInSection section: Int) -> Int

// Method with two parameters, tableView and indexPath.
// The question mark means it returns an optional IndexPath 
// object (may also return nil).
override func tableView(
  _ tableView: UITableView, 
  willSelectRowAt indexPath: IndexPath) -> IndexPath?
// Calling a method on the lists object:
lists.append(checklist)

// Calling a method with more than one parameter:
tableView.insertRows(at: indexPaths, with: .fade)
class DataModel {
  func loadChecklists() {
    . . .    
    sortChecklists()  // this method also lives in DataModel
  }

  func sortChecklists() { 
    . . . 
  }
}
  func loadChecklists() {
    . . .    
    self.sortChecklists()
  }
@IBAction func cancel() {
  delegate?.itemDetailViewControllerDidCancel(self)
}

参数

通常方法有一个或多个 参数, so they can work with multiple data items. A method that is limited to a fixed set of data is not very useful or reusable. Consider sumValuesFromArray(), a method that has no parameters:

class MyObject {
  var numbers = [Int]()

  func sumValuesFromArray() -> Int {
    var total = 0
    for number in numbers {
      total += number
    }
    return total
  }
}
func sumValues(from array: [Int]) -> Int {
  var total = 0
  for number in array {
    total += number
  }
  return total
}
func downloadImage(
  for searchResult: SearchResult,  
  withTimeout timeout: TimeInterval, 
  andPlaceOn button: UIButton
) {
  . . .
}
downloadImage(for: result, withTimeout: 10, andPlaceOn: imageButton)
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

做出决定

The if 陈述 looks like this:

if count == 0 {
  text = "No Items"
} else if count == 1 {
  text = "1 Item"
} else {
  text = "\(count) Items"
}

比较运算符

你用 比较运算符 要在两个值之间执行比较:

let a = "Hello, world"
let b = "Hello," + " world"
print(a == b)             // prints true

逻辑运营商

您可以使用 逻辑 运营商结合两个表达式:

if ((this && that) || (such && so)) && !other {
  // statements
}
if ((this and that) or (such and so)) and not other {
  // statements
}
if ( 
      (this and that)
            or
      (such and so)
   )
   and
      (not other)

switch statement

Swift has another very powerful construct in the language for making decisions, the switch statement:

switch condition {
  case value1:
    // statements

  case value2:
    // statements

  case value3:
    // statements

  default:
    // statements
}
if condition == value1 {
  // statements
} else if condition == value2 {
  // statements
} else if condition == value3 {
  // statements
} else {
  // statements
}
switch difference {
  case 0:
    title= "Perfect!"
  case 1..<5:
    title= "You almost had it!"
  case 5..<10:
    title= "Pretty good!"
  default:
    title= "Not even close..."
}

return statement

Note that if and return can be used to return early from a method:

func divide(_ a: Int, by b: Int) -> Int {
  if b == 0 {
    print("You really shouldn't divide by zero")
    return 0
  }
  return a / b
}
func performDifficultCalculation(list: [Double]) {
  if list.count < 2 {
    print("Too few items in list")
    return
  }

  // perform the very difficult calculation here
}
func performDifficultCalculation(list: [Double]) {
  if list.count < 2 {
    print("Too few items in list")
  } else {
    // perform the very difficult calculation here
  }
}
func someMethod() {
  if condition1 {
    if condition2 {
      if condition3 {
        // statements
      } else {
        // statements
      }
    } else {
      // statements
    }
  } else {
    // statements
  }
}
func someMethod() {
  if !condition1 {
    // statements
    return
  }

  if !condition2 {
    // statements
    return
  }

  if !condition3 {
    // statements
    return
  }

  // statements
}
func someMethod() {
  guard condition1 else {
    // statements
    return
  }
  guard condition2 else {
    // statements
    return
  }
  . . .

循环

You’ve seen the for...in 陈述 for looping through an array:

for item in items {
  if !item.checked {
    count += 1
  }
}
for item in items where !item.checked {
  count += 1
}

通过数字范围循环

Some languages have a for 陈述 that looks like this:

for var i = 0; i < 5; ++i {
  print(i)
}
0
1
2
3
4
for i in 0...4 {   // or 0..<5
  print(i)
}
for i in stride(from: 0, to: 5, by: 1) {
  print(i)
}

while statement

The for 陈述 is not the only way to perform loops. Another very useful looping construct is the while statement:

while something is true {
  // statements
}
repeat {
  // statements
} while something is true
var count = 0
var i = 0
while i < items.count {
  let item = items[i]
  if !item.checked {
    count += 1
  }
  i += 1
}
var found = false
for item in array {
  if item == searchText {
    found = true
    break
  }
}
var uncheckedItems = items.filter { item in !item.checked }

对象

对象是它的全部。它们将具有功能的数据与连贯,可重复使用的单位组合 - 即,如果您正确地写信!

class MyObject {
  var text: String
  var count = 0
  let maximum = 100

  init() {
    text = "Hello world"
  }

  func doSomething() {
    // statements
  }
}

特性

有两种类型的属性:

var indexOfSelectedChecklist: Int {
  get {
    return UserDefaults.standard.integer(
      forKey: "ChecklistIndex")
  }
  set {
    UserDefaults.standard.set(
      newValue, 
      forKey: "ChecklistIndex")
  }
}

方法

有三种方法:

let myInstance = MyObject()   // create the object instance
. . .
myInstance.doSomething()      // call the method
class MyObject {
  . . .

  class func makeObject(text: String) -> MyObject {
    let m = MyObject()
    m.text = text
    return m
  }
}

let myInstance = MyObject.makeObject(text: "Hello world")
class MyObject {
  . . .

  init(text: String) {
    self.text = text
  }
}

let myInstance = MyObject(text: "Hello world")

协议

除了对象外,还可以定义 协议。协议只是方法名称列表,可能是属性:

protocol MyProtocol {
  func someMethod(value: Int)
  func anotherMethod() -> String
}
class MyObject: MyProtocol {
  . . .
}
var m1: MyObject = MyObject()
var m2: MyProtocol = MyObject()

有一个技术问题?想报告一个错误吗? 您可以向官方书籍论坛中的书籍作者提出问题和报告错误 这里.

有反馈分享在线阅读体验吗? 如果您有关于UI,UX,突出显示或我们在线阅读器的其他功能的反馈,您可以将其发送到设计团队,其中表格如下所示:

© 2021 Razeware LLC

您可以免费读取,本章的部分显示为 混淆了 文本。解锁这本书,以及我们整个书籍和视频目录,带有Raywenderlich.com的专业订阅。

现在解锁

要突出或记笔记,您需要在订阅中拥有这本书或自行购买。