Last active
June 9, 2019 07:56
-
-
Save ykrods/98962a804f037d78da5f29f86ebb6c23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Swift (v4.2.1) Quick Start | |
* | |
* see: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html | |
*/ | |
// variable | |
var n = 1 | |
// constant | |
let DEFAULT_NAME = "FOO" | |
// print with format | |
print("name is \(DEFAULT_NAME)") | |
// optional variable | |
// == `var x: Optional<Int>` | |
var x :Int? | |
// print with nil-aware | |
print(String(describing: x)) | |
// Bitwise Operator | |
print(1 & 2) // AND | |
print(1 | 2) // OR | |
// enum with method | |
enum Mode: Int { | |
case READ = 1 | |
case WRITE = 2 | |
case READ_WRITE = 3 | |
public func writeble () -> Bool { | |
// ??? Binary operator '|' cannot be applied to operands of type 'Int' and '_' | |
// return self.rawValue | .WRITE | |
return self == .WRITE || self == .READ_WRITE | |
} | |
} | |
let mode:Mode = .READ | |
print(mode.writeble()) | |
// switch with enum | |
switch mode { | |
case .WRITE: | |
print("WRITE") | |
break; | |
default: | |
print("DEFAULT") | |
break; | |
} | |
// unwrapping | |
struct Point { | |
x: Int | |
y: Int | |
} | |
var point: Point? | |
point = Point(x: 1, y:2) | |
if let px = point?.x { | |
print(px + 1) // `print(p.x + 1)` cause error (nil-able) | |
} | |
// guard (unverified snippet) | |
func distance(_ to: Point, from: Point?) { | |
guard let f = from else { f = Point(x:0,y:0) } | |
} | |
// Omitting Argument Labels | |
// ラベルなし = ポジション引数 | |
func twice(_ x:Int) -> Int { | |
return x * 2 | |
} | |
print(twice(2)) | |
// class with computed property | |
class Person { | |
private var _age: Int | |
// initializer | |
init(age: Int) { | |
self._age = age | |
} | |
// computed property | |
var age: Int { | |
get { | |
return self._age | |
} | |
set (age) { | |
self._age = age | |
} | |
} | |
// read-only computed property | |
var adult: Bool { | |
return 20 <= self.age | |
} | |
} | |
var p = Person(age: 20) | |
p.age = p.age + 1 | |
print(p.age) | |
print(p.adult) | |
// inspect type | |
print(type(of: p.adult)) | |
// function with callback | |
func fetch(success: @escaping (_ result: String) -> Void, | |
failure: @escaping (_ error: Error) -> Void) { | |
success("OK") | |
} | |
// closure | |
fetch(success: { (result) in | |
print("result is \(result)") | |
}, failure: { (error) in | |
print("error: \(error)") | |
}) | |
// trailing closure | |
// (初見で読めない & メリットがわからない) > map 等の高階関数を書く時にオシャレしたい?? | |
fetch(success: { (result) in | |
print("result is \(result)") | |
}) { (error) in | |
print("error: \(error)") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment