objc2swift 〜 Objective-C から Swift への「コード&パラダイム」シフト
Post on 06-Jan-2017
5368 Views
Preview:
Transcript
objc2swift Objective-C Swift &
@taketo1024
2015/11/11 iOS 9 Bootcamp @ dots. by Classmethod, inc.
About Me
() iOS iOS 4 (Xcode 3.x ) 31 1()
11/21 () 5 11/15 ()
Objective-C Swift
1 ObjC iOS
44 iOS
Swift
Bridging-Header
ObjC Swift
ObjC Swift
Swift
ObjC Swift
ObjC Swift
@interface MyClass class MyClass
@property NSString *text; var text: String
@protocol MyProtocol protocol MyProtocol
@interface MyClass(Hoge) extension MyClass
2
ANTLR...?
ANTLR v4
http://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.orghttp://www.antlr.org
ANTLR Parser
2 ANTLR
ANTLR ObjC
Swift
Java Scala
class A : NSObject {
}
Swift
merge .h & .m
@interface MyClass : NSObject
@end
@implementation MyClass
@end Obj-C
Obj-C Swift
convert method-call
self.somethingWithArg1("hello", arg2:0)
Swift
[self somethingWithArg1:@"hello" arg2:0];
Obj-C
control-flow
for var i = 0; i < 10; i++ {
}
Swift
for (int i = 0; i < 10; i++) {
}
Obj-C
& many more! primitive-types
class-method
enum
protocol
property
block -> closure
stringWithFormat
error reporting
Web UI
20%
40%
40%
20%
80%
N=5N=5
SwiftObjective-CSwift
Swift Objective-C Swift objc2swift
Scala
DEMO
OpenSourced
https://github.com/yahoojapan/objc2swift
WebUI
https://github.com/yahoojapan/objc2swift
Goodbye ObjC !!!
No more too many @s! No more YES / NO ! No more [brackets forMethodCall] !
https://twitter.com/marcote_torres/status/473536682353262592/photo/1
Swift
So many ? s... So many if let s... unexpectedly found nil while blabla...
let result = try? NSJSONSerialization.JSONObjectWithData()
let name = ((result?["person"] as? [String: AnyObject])?["name"] as? String)
if let name = name { print("My name is: \(name)") }
Swift Swift ObjC Objective-C without the C ...? wtf
Swift
ObjC / Foundation
Swift Swift
0. Swift
1. Optional
2. First-Class
3. Protocol Oriented
0. Swift
Objective-C
19831985 Apple Steve Jobs NeXT Computer
1997Apple NeXT 2001 Mac OS X Cocoa
Foundation NS OS NeXTSTEP
ObjC C Smalltalk
C C
ObjC @ C
typedef struct objc_class *Class; struct objc_class {
struct objc_class *isa;
struct objc_class *super_class;
const char *name;
};
typedef struct objc_object {
class isa;
} *id;
2005Objective-C -
http://news.mynavi.jp/column/objc/014/
Obj-C
Objective-C Swift
GCC
Objective-C
1983
GCC
Objective-C 2.0
2007
LLVM
ModernObjective-C
2012
Swift 1.0
2014
SwiftApple
LLVM
Clang swiftc
Apple LLVM Swift
http://codezine.jp/article/detail/8768
Swift ()
Objective-C
The Swift language also greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
http://nondot.org/sabre/
Chris Lattner
ObjC
Strongly Typed (w/ Optional Type)
Functional
Protocol-Oriented
1. Optional
Apple
if let johnsStreet = john.residence?.address?.street { print("John's street name is \(johnsStreet).") } else { print("Unable to retrieve the address.") }
Swift also introduces optional types, which handle the absence of a value. Optionals say either there is a value, and it equals x or there isnt a value at all. Using optionals is similar to using nil with pointers in Objective-C, but they work for any type, not just classes.
nil ?
nil ?
public enum Optional : NilLiteralConvertible { case None case Some(Wrapped) }
Optional enum Int? Optional
Optional Optional
nil Optional None
Swift Standard Library
Optional
Functors, Applicatives, And Monads In Pictures
http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
Optional 0 1 Array
let maybeInt : Optional = .Some(1)
let actualInt = maybeInt!
let maybeInt : Optional = 1
let actualInt = maybeInt!
let maybeInt : Optional = .Some(1)
let actualInt = maybeInt!
let actualInt = maybeInt!
let maybeInt : Array = [1]
let actualInt = maybeInt[0]
let maybeInt : Optional = nil
let actualInt = maybeInt! // fatal error: unexpectedly found nil while unwrapping an Optional value
let maybeInt : Array = []
let actualInt = maybeInt[0] // fatal error: Array index out of range
nil
let maybeInt : Optional = .Some(1)
if let actualInt = maybeInt { print("int: \(actualInt)") }
let maybeInt : Array = [1]
for actualInt in maybeInt { print("int: \(actualInt)") }
if let 1 for in for
Swift Optional
Optional Objective-C nil
Optional
guard let
let maybeInt: Optional = 1
guard let actualInt = maybeInt else { fatalError() }
print("value: \(actualInt)")
guard let
let value: Optional = 1
guard let value = value else { fatalError() }
print("value: \(value)")
unwrap
guard let
let value: Optional = 1 guard let value = value else { fatalError() }
print("value: \(value)")
!!!
Optional
Int
guard let
2. First-Class
let a = [2, 3, 1, 4]
a.sort() // [4, 3, 2, 1]
let a = [2, 3, 1, 4]
a.sort() // [4, 3, 2, 1]
sort (T, T) -> Bool
let a = [2, 3, 1, 4]
let lt: (Int, Int) -> Bool = (
ObjC Swift
let a = [2, 3, 1, 4] // [2, 3, 1, 4] let b = a.map {$0 * 2} // [4, 6, 2, 8] let c = b.filter {$0 < 5} // [4, 2]
map filter
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var result = [UICollectionViewLayoutAttributes]() for i in 0 ..< items.count { let indexPath = NSIndexPath(forItem: i, inSection: 0) let attr = layoutAttributesForItemAtIndexPath(indexPath)
if attr.alpha == 0 { continue } if !CGRectIntersectsRect(attr.frame, rect) { continue } result.append(attr) } return result }
map filter
before
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let indexPaths = (0 ..< items.count).map { NSIndexPath(forItem: $0, inSection: 0) } let attrs = indexPaths.map( layoutAttributesForItemAtIndexPath )
let attrsInScreen = attrs.filter { $0.alpha > 0 } .filter{ CGRectIntersectsRect($0.frame, rect)}
return attrsInScreen }
map filter
after
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return (0 ..< items.count) .map { NSIndexPath(forItem: $0, inSection: 0) } .map ( layoutAttributesForItemAtIndexPath ) .filter { $0.alpha != 0 } .filter { CGRectIntersectsRect($0.frame, rect)} }
let a : Optional = 1 // .Some(1) let b = a.map { $0 * 2 } // .Some(2)
Optional map
.Some(1) [1]
let a : Optional = "1" // .Some("1") let b = a.map { Int($0) } // .Some( .Some(1) )
let s : Optional = "hehe" // .Some("hehe") let t = s.map { Int($0) } // .Some( .None )
map Optional 2
String -> Int Optional
let a : Optional = "1" // .Some("1") let b = a.flatMap { Int($0) } // .Some(1)
let s : Optional = "hehe" // .Some("hehe") let t = s.flatMap { Int($0) } // .nil
flatMap !
let a = ["1", "2", "heh", "4", "lol"] let b = a.flatMap{ Int($0) } // [1, 2, 4]
Optional flatMap filter
https://codeiq.jp/magazine/2015/07/27113/
ObjC Swift
Scala Haskell
Promise ReactiveUI
3. Protocol-Oriented
WWDC2015 - Protocol-Oriented Programming in Swift
https://developer.apple.com/videos/play/wwdc2015-408/
Swift is the first protocol oriented language.
Swift protocol
Java interface
Scala trait mix-in
Haskell type class AdHoc
Haskell class Eq a where (==), (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y)
data Point = Pt Double Double
instance Eq Point where (Pt x y) == (Pt x' y') = x == x' && y == y'
Eq
Point Eq
http://walk.wgag.net/haskell/typeclass.html
http://walk.wgag.net/haskell/typeclass.html
public protocol Equatable {
public func ==(lhs: Self, rhs: Self) -> Bool
}
struct Point: Equatable { let x, y: Double }
func ==(p1: Point, p2: Point) -> Bool { return p1.x == p2.x && p1.y == p2.y }
Equatable
Point Equatable
Scala / Haskell U Protocol
protocol AddMonoid { static var zero: Self { get } static func plus(lhs: Self, _ rhs: Self) -> Self }
extension Int: AddMonoid { static var zero: Int { return 0 } static func plus(lhs: Int, _ rhs: Int) -> Int { return lhs + rhs } }
extension String: AddMonoid { static var zero: String { return "" } static func plus(lhs: String, _ rhs: String) -> String { return lhs + rhs } }
extension SequenceType where Generator.Element: AddMonoid { func sum() -> Generator.Element { return reduce(Generator.Element.zero) { Generator.Element.plus($0, $1) } } }
[1, 2, 3].sum() // 6 ["abc", "def", "ghi"].sum() // "abcdefghi"
class-oriented vs protocol-oriented ()
struct
Protocol
protocolA
protocolB
protocol-oriented
Swift protocol-oriented Foundation / UIKit
Self Requirement
protocol MyProtocol: Equatable {}
struct A: MyProtocol {} struct B: MyProtocol {}
let a: [MyProtocol] = [A(), B()] // protocol 'MyProtocol' can only be used as a generic constraint because it has Self or associated type requirements
extension protocol-oriented
Swift Foundation / UIKit
()
Thanks!
Twitter: taketo1024Blog: http://taketo1024.hateblo.jp/
https://twitter.com/taketo1024http://taketo1024.hateblo.jp/https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/taketo1024https://twitter.com/marcote_torres/status/473536682353262592/photo/1
top related