Skip to content

Instantly share code, notes, and snippets.

@canujohann
Last active February 23, 2016 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save canujohann/6591d2b7ae03a643ab88 to your computer and use it in GitHub Desktop.
Save canujohann/6591d2b7ae03a643ab88 to your computer and use it in GitHub Desktop.
swift メモ
Functions definition
func someFunction(a: Int) { /* ... */ }
Tuples definition
let someTuple: (Double, Double) = (3.14159, 2.71828)

var t = (10, 20, 30)
t.0 = t.1

let x = [10, 3, 20, 15, 4]
    .sort()
    .filter { $0 > 5 }
    .map { $0 * 100 }
Typealias
typealias Point = (Int, Int)
let origin: Point = (0, 0)
Enumerations
enum Number {
    case Integer(Int)
    case Real(Double)
}

enum ExampleEnum: Int {
    case A, B, C = 5, D
}
Arrays
let someArray: Array<String> = ["Alex", "Brian", "Dave"]
let someArray: [String] = ["Alex", "Brian", "Dave"]
Dictionnaries
let someDictionary: [String: Int] = ["Alex": 31, "Paul": 39]
let someDictionary: Dictionary<String, Int> = ["Alex": 31, "Paul": 39]
Optional Type

The type Optional is an enumeration with two cases, None and Some(Wrapped),

var optionalInteger: Int?
var optionalInteger: Optional<Int>

# no runtime error if nil
optionalInteger = 42
optionalInteger! // 42
Implicitly Unwrapped
var implicitlyUnwrappedString: String!
var implicitlyUnwrappedString: ImplicitlyUnwrappedOptional<String>
Protocol
protocol SomeProtocol {
    // protocol definition goes here
}

struct SomeStructure: FirstProtocol, AnotherProtocol {
    // structure definition goes here
}

class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}
metatype
if someInstance.dynamicType === someInstance.self {}


class AnotherSubClass: SomeBaseClass {
    let string: String
    required init(string: String) {
        self.string = string
    }
    override class func printClassName() {
        print("AnotherSubClass")
    }
}
let metatype: AnotherSubClass.Type = AnotherSubClass.self
let anotherInstance = metatype.init(string: "some string")
GRAMMAR OF A METATYPE TYPE

lazy

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

class DataImporter {
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a non-trivial amount of time to initialize.
    */
    var fileName = "data.txt"
    // the DataImporter class would provide data importing functionality here
}
 
class DataManager {
    lazy var importer = DataImporter()
    var data = [String]()
    // the DataManager class would provide data management functionality here
}

try

try
try?
try!
Closures
myFunction {
    (x: Int, y: Int) -> Int in
    return x + y
}
 
myFunction {
    (x, y) in
    return x + y
}
 
myFunction { return $0 + $1 }
 
myFunction { $0 + $1 }
wildcard

explicitly ignore a value during an assignment.

(x, _) = (10, 20)
// x is 10, and 20 is ignored
Constructors
class SomeSubClass: SomeSuperClass {
    override init() {
        // subclass initialization goes here
        super.init()
    }
}
Forced-Value Expression

A forced-value expression unwraps an optional value that you are certain is not nil.

var x: Int? = 0
x!++
// x is now 1
Optional-Chaining Expression

An optional-chaining expression provides a simplified syntax for using optional values in postfix expression

var c: SomeClass?
var result: Bool? = c?.property.performAction()
Guard Statement
guard condition else {
    statements
}
Defer Statement
func f() {
    defer { print("First") }
    defer { print("Second") }
    defer { print("Third") }
}
Do Statement
do {
    try expression
    statements
} catch pattern 1 {
    statements
} catch pattern 2 where condition {
    statements
}
Computed Variables and Computed Properties
var variable name: type {
	get {
	    statements
	}
	set(setter name) {
	    statements
	}
}
In-Out Parameters
func swapInt(inout a:Int, inout b:Int)
{
    var tmp:Int
    tmp = a
    a = b
    b = tmp
}

var x:Int = 2
var y:Int = 3

println("x:\(x)") //x:2
println("y:\(y)") //y:3

swapInt(&x, &y)

//参照渡しなのでSwapされている
println("x:\(x)") //x:3
println("y:\(y)") //y:2
Curried Functions

2 functions are similar :

func addTwoInts(a a: Int, b: Int) -> Int {
    return a + b
}
func addTwoIntsCurried(a a: Int) -> (Int -> Int) {
    func addTheOtherInt(b: Int) -> Int {
        return a + b
    }
    return addTheOtherInt
}
Rethrowing Functions
enum NumberError:ErrorType {
    case ExceededInt32Max
}

func functionWithCallback(callback:(Int) throws -> Int) rethrows {
    try callback(Int(Int32.max)+1)
}

do {
 try functionWithCallback({v in if v <= Int(Int32.max) { return v }; throw NumberError.ExceededInt32Max})
}
catch NumberError.ExceededInt32Max {
    "Error: exceeds Int32 maximum"
}
catch {
}
Infix Prefix Postfix

To check

Attributes (@)
@available(iOS 8.0, OSX 10.10, *)
class MyClass {
    // class definition
}
wildcard pattern
for _ in 1...3 {
    // Do something three times.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment