Swift Learning Notes-1

Optional

An Optional is just an enum

enum Optional<T> { // the <T> is the generic like as in Array<T>
  case None
  case Some(T)
}

e.g.

  • let x: String? = nil <=> let x = Optional<String>.None
  • let x: String? = "hello" <=> let x = Optional<String>.Some("hello")
  • var y = x! <=>
switch x {
  case Some(let value): y = value
  case None: // raise an exception
}
  • if let
let x: String? = ...
if let y = x {
  // do something with y
}

<=>

switch x {
    case .Some(let y): 
      // do something with y
    case .None: 
      break
}

Optionals can be "chained"

var display: UILabel?
if let label = display {
    if let text = label.text {
      let x = text.hashValue
      ...
    }
}

can be written as below, which is much nicer

if let x = display?.text?.hashValue{ ... }

There is also an Optional "default" operator ??

What if we want to put a String into a UILabel, but if it is nil, put " " (space) in that UILabel?

let s: String? ... // might be nil
if s != nil {
  display.text = s
} else {
  display.text = " "
}

... can be expressed much more simply this way ...

display.text = s ?? " "

Tuples

A type out of other types by grouping them

e.g.

let x: (String, Int, Double) = ("hello", 5, 0.85)
let (word, number, value) = x // tuple elements named when accessing the tuple
print(word) // prints hello
print(number) // prints 5

... or tuple elements can be named when the tuple is declared ...

let x: (w: String, n: Int, v: Double) = ("hello", 5, 0.85)
print(x.w) // prints hello
print(x.n) // prints 5

renames the tuple's elements on access

let (wrd, num, val) = x

Range

A range in Swift is just two end points
Range is generic (e.g. Range<T>)

pseudo-representation of Range:

struct Range<T> {
  var startIndex: T
  var endIndex: T
}

An array's range would be a Range<Int>
Warning: A String's subrange is not Range<Int>, it's Range<String.Index>
e.g.

let array = ["a", "b", "c", "d"]
let subArray1 = array[2...3] // ["c", "d"]
let subArray2 = array[2..<3] // ["c"]
for i in 1...10 {}

Data Structure in Swift

Classes, Structures, Enumerations

These are the 3 fundamental building blocks of data structures in Swift

Similarities

  • Declaration syntax ...
class CalculatorBrain {
}
struct Vertex {
}
enum Operation {
}
  • Properties and Functions
  • Initializers (not enum)

Differences

  • Inheritance (class only)
  • Value type (struct, enum) vs. Reference type (class)
  • struct and enum are passed around by value
  • class pass pointers around listed in heap

Value vs. Reference

Value

  • Copied when passed as an argument to a function
  • Function parameters are constant
  • any func that can mutate a struct/enum with key word mutating

Reference

  • Stored in heap and reference counted (automatically)
  • Constant pointers to a class (let) still can mutate by calling methods and changing properties
  • When passed as an argument, does not make a copy (just passing a pointer)

Array

Interesting Array<T> methods

  • Filter method: filter any "undesirables" out
filter(includeElement: (T) -> Bool) -> [T]
let bigNumbers = [2,3,15,20,9].filter({ $0 > 10 }) //bigNumbers = [15,20]
  • map take the closure, which converts each element in the array to something else.
map(transform: (T) -> U) -> [U]
let intToString: [String] = [1,2,3].map { String($0) }
  • Reduce an entire array to a single value
reduce(initial: U, combine: (U, T) -> U) -> U
let sum: Int = [1,2,3].reduce(0) { $0+$1 } //adds up all elements in the array

Dictionary

  • use a tuple with for-in to enumerate a Dictionary
for (key, value) in pac10teamRankings {
  print("\(key) = \(value)")
}

String

  • The simplest way to deal with the characters in a string is via this property
var characters: String.CharacterView { get }
  • Other String Methods
    • startIndex -> String.Index
    • endIndex -> String.Index
    • hasPrefix(String) -> Bool
    • hasSuffix(String) -> Bool
    • capitalizedString -> String
    • lowercaseString -> String
    • uppercaseString -> String
    • componentsSeparatedByString(String) -> [String]
      //"1,2,3".csbs(",") = ["1","2","3"]

Initialization

  • There are two types of inits in a class: convenience and designated
  • A designated init must (and can only) call a designated init that is in the immediate superclass.
  • Before calling a superclass's init, you must initialize all properties introduced by your class
  • Before you assign a value to an inherited property, you must call a superclass's init.
  • A convenience init must (and can only) call an init in its own class.
  • A convenience init must call that init before it can set any property values.

AnyObject

  • Optional Conversion with as?
let ao: AnyObject = ...
if let foo = ao as? SomeClass {
  // we can use foo and know that it is of type SomeClass in here
}

欢迎转载,转载请注明出处。访问我的个人主页,查看更多。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容