Skip to content

Instantly share code, notes, and snippets.

@haranicle
haranicle / CodePiece.swift
Created July 25, 2015 06:13
do-catchについて #cswift #CodePiece
// エラーハンドリング専用構文
do {
// エラーが発生する可能性があるコード
} catch {
// エラー発生時の処理
}
// 例
do {
@haranicle
haranicle / CodePiece.swift
Created July 25, 2015 06:33
PatternMatchingについて #cswift #CodePiece
if case let .OSX(version) = platform {
print(version)
}
if case let value? = optionalValue {
}
if case let (a?, b?, c?) = (optionalA, optionalB, optionalC) {
// optionalA,B,Cすべてがoptionalじゃないときだけ実行される
print(\(a)\(b)\(c))
@haranicle
haranicle / CodePiece.swift
Created July 31, 2015 16:45
??? #CodePiece
Realm().write {
Realm().deleteAll()
}
let turtle = Animal()
turtle.name = "Turtle"
turtle.legCount = 4
Realm().write {
Realm().add(turtle)
@haranicle
haranicle / imgdiff
Created August 12, 2015 03:21
imgdiff a.jpg b.jpg diff.jpg
alias imgdiff='composite -compose difference'
@haranicle
haranicle / CodePiece.swift
Created December 15, 2015 16:13
Captureの挙動テスト #CodePiece
class HTMLElement {
let name: String
let text: String?
// プロパティでasHTMLへのstrong参照を持っている
lazy var asHTML: Void -> String = { // nameとtextを使いたいからlazy
// Closure内でselfのプロパティをキャプチャしている
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
@haranicle
haranicle / CodePiece.swift
Created February 6, 2016 05:13
letで再帰 #CodePiece #cswift
let sum: ([Int]) -> Int
sum = { values in
if values.isEmpty {
return 0
}
else {
return values.first! + sum(Array(values.dropFirst()))
}
}
@haranicle
haranicle / CodePiece.swift
Created February 6, 2016 05:32
letなstruct #CodePiece #cswift
struct Location {
var x:Int
var y:Int
}
var l1 = Location(x: 10, y: 20)
l1.x = 30
let l2 = Location(x: 10, y: 20)
l2.x = 30 // Cannot assign to property
@haranicle
haranicle / CodePiece.swift
Last active February 10, 2016 06:50
Swizzlingメモ #CodePiece
public override static func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
struct SwizzlingSelector {
let original:Selector
let swizzled:Selector
}
@haranicle
haranicle / CodePiece.swift
Last active February 16, 2016 09:40
なぜなのか #CodePiece
protocol P: Hashable {}
func ==(lhs: S, rhs: S) -> Bool { return lhs.name == rhs.name }
struct S: P {
var name = "struct"
var hashValue: Int { get{ return name.hash } }
}
let setS: Set<S> = [S()]
let setP: Set<P> = [S()] // Protocol 'P' can only be used as a generic constraint because it has Self or assosiated type requirements
@haranicle
haranicle / CodePiece.swift
Created February 16, 2016 10:04
@es_kumagai 訂正!仰るとおり中でSelfを扱っているとダメでした。 #CodePiece
protocol P1 {
}
protocol P2 {
typealias A = Self
}
let arr1: Array<P1> = []
let arr2: Array<P2> = [] // Protocol 'P2' can only be used as a generic constraint because it has Self or associated type requirements