Iacutone.rb

coding and things

Swift Basics

| Comments

String Interpolation

1
2
3
4
5
var name = "Eric"

println("Hello, \(name)")

// "Hello, Eric"

Dictionaries

1
2
3
4
5
6
7
8
9
var response = ["id":14,"email":"test@email.com"]

let id = response["id"]

// 14

let email = response["email"]

// "test@email.com"

Tuples

Unnamed Tuples

1
2
3
4
5
6
7
8
9
10
11
var coordinates = (100, 999)

let (lat, lon) = coordinates

println("Latitude is \(lat)")

// "Latitude is 100"

println("Longtitude is \(lon)")

// Longitude is 999

Named Tuples

1
2
3
4
5
6
7
8
9
10
11
12
13
var response = (code: 200, message: "All good")

response.0
// 200

response.1
// "All good"

response.code
// 200

respsonse.message
// "All good"

Swift Classes

Creating a class

Person.swift
1
2
3
4
5
6
7
8
9
10
11
12
13

class Person: NSObject {
  var name: String
  var email: String
  var zip: Int

  init(name: String, email: String, zip: Int) {
    self.name = name
    self.email = email
    self.zip = zip
    super.init()
  }
}

Create data for Person Class

SampleData.swift
1
2
3
let personData = [
  Person(name: "Eric", email: "eric.iacutone@gmail.com", zip: 12345)
]

Instantiating Person Class

PersonViewController.swift
1
var person:Array = personData

Now, if you copy and paste the the files into a XCode Playground, you can call methods on your person object.

Playground.swift
1
2
3
4
5
person.count
// 1

person.first?.zip
// 12345

Enums

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. - Swift docs

Use an enum when you need a consistent data value.

1
2
3
4
5
6
7
8
9
10
11
12
enum CountryType:String {
    case UnitedStates = "United States"
    case Spain = "Spain"

    init() {
      self = .UnitedStates
    }
}

var type = CountryType.UnitedStates.rawValue

// "United States"

Structs

A struct allows you to create a structured data type which provides storage of data using properties and extending its functionality via methods. -Tree House

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Person {
    var name: String
    var email: String
    var country: CountryType
}

var person = Person(name: "Eric", email: "eric.iacutone@gmail.com", country: CountryType.UnitedStates)

person.name

// "Eric"

person.country.rawValue

// "United States"

Comments