Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Refactoring an Ugly Objective-C with Swift
Search
Konstantin
February 11, 2016
Programming
0
220
Refactoring an Ugly Objective-C with Swift
Refactoring an Ugly Objective-C with Swift
Konstantin
February 11, 2016
Tweet
Share
More Decks by Konstantin
See All by Konstantin
How does complier see your app
konstantinkoval
4
120
Swift Package Manager
konstantinkoval
2
160
Swift rEvolution
konstantinkoval
1
230
React Native - from a mobile (iOS) developer prospective
konstantinkoval
0
61
Swift - Pushing technology limits
konstantinkoval
1
220
WatchKit
konstantinkoval
0
57
Intro in WatchKit and Watch apps
konstantinkoval
0
53
Functional Swift
konstantinkoval
1
130
I love swift.pdf
konstantinkoval
1
180
Other Decks in Programming
See All in Programming
Spatial Rendering for Apple Vision Pro
warrenm
0
110
CQRS+ES の力を使って効果を感じる / Feel the effects of using the power of CQRS+ES
seike460
PRO
0
130
【re:Growth 2024】 Aurora DSQL をちゃんと話します!
maroon1st
0
780
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
780
Effective Signals in Angular 19+: Rules and Helpers
manfredsteyer
PRO
0
100
Fibonacci Function Gallery - Part 1
philipschwarz
PRO
0
220
Effective Signals in Angular 19+: Rules and Helpers @ngbe2024
manfredsteyer
PRO
0
140
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
430
生成AIでGitHubソースコード取得して仕様書を作成
shukob
0
440
42 best practices for Symfony, a decade later
tucksaun
1
180
[JAWS-UG横浜 #76] イケてるアップデートを宇宙いち早く紹介するよ!
maroon1st
0
460
tidymodelsによるtidyな生存時間解析 / Japan.R2024
dropout009
1
790
Featured
See All Featured
Designing for Performance
lara
604
68k
Git: the NoSQL Database
bkeepers
PRO
427
64k
The World Runs on Bad Software
bkeepers
PRO
65
11k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
191
16k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
251
21k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.9k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
95
17k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
Automating Front-end Workflow
addyosmani
1366
200k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
5
450
The Art of Programming - Codeland 2020
erikaheidi
53
13k
Transcript
Refactoring Ugly Objective-C
I am - !" ! - Swift ! - Programming
! - Swift Package Manager http://swifthighperformance.com ! Swift Hight Performance
Swift Syntax and Expressiveness ~ 30% less code
Let's talk about Objective-C
Amazing Feature № 1 KKOStorage *storage = [KKOStorage new]; [storage
saveItem:@"New item"]; KKONetwork *network = [KKONetwork new]; [network uploadItem:@"Some stuff"];
Amazing Feature № 1 KKOStorage *storage = [KKOStorage new]; [storage
saveItem:@"New item"]; KKONetwork *network = [KKONetwork new]; [network uploadItem:@"Some stuff"]; [network saveItem:@"Some stuff"]; ❗Error❗
BUT
[network performSelector: @selector(saveItem:)]; id network = [[KKONetwork alloc] init]; [network
saveItem:@"!"]; [network arrayByAddingObjectsFromArray: @[ @10 ]]; [network URLByAppendingPathComponent:@"/me.com"];
But who does ever use id?
! Does! // @interface NSObject <NSObject> // - (id)copy; NSMutableArray
*ar = [NSMutableArray arrayWithArray:@[@1, @1]]; NSMutableArray *aCopy = [ar copy]; // it's a NSArray [aCopy addObject: @2]; //Crash here!!
VS Swift let storage = Storage() storage.saveItem("Apple") let network =
Network() network.uploadItem("Item") // network.saveItem("i") // Error! Always!
VS Swift let any: Any = Network() // any.saveItem("i") //
Can't!! if let any = any as? Storage { any.saveItem("i") }
safety += 1
Objc id vs Swift Any
Objc id Can do Anything. Whatever you Want! id some;
[some URLCache]; [some stringByAppendingString:@":("];
Swift Any Can't do Nothing let any: Any = "String"
any. //Any is empty. It has 0 methods print(any)
safety += 2
3: Initialization
- (instancetype)init { self = [super init]; if (self) {
// Init ivars! // Don't access properties!!! } return self; }
Go Crazy - (instancetype)init { return 0; // -1, etc
} - (instancetype)init { return [self init]; } - (instancetype)init { return nil; } - (instancetype)init { // Do whatever You Want }
@interface KKOArticle : NSObject @property (nonatomic, readonly, strong) NSString *title;
@property (nonatomic, readonly, strong) NSString *text; @property (nonatomic, readonly, strong) NSDate *date; - (instancetype)initWith:(NSString *)title text:(NSString *)text date:(NSDate *)date; @end @implementation KKOArticle - (instancetype)initWith:(NSString *)title text:(NSString *)text date:(NSDate *)date { self = [super init]; if (self) { _title = title; _text = text; _date = date; } return self; } @end KKOArticle *article = [[KKOArticle alloc] initWith:@"title" text:@"text" date:[NSDate date]];
No boilerplate code! init () init () { // !
Just put code here }
Can't go Crazy :( init () { // - must
initialize all properties // - super.init is required when has a superclass // - can't access properties and methods until filly initialized // - very safe }
Swift struct Article { let title: String let text: String
let date: NSDate } Article(title: "title", text: "Text", date: NSDate())
Safety += 3 Clean += 2
Optionals !
Fun Quiz a + b = c b + a
= c
NSString *a; [a stringByAppendingString:@"b"];
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a];
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a]; // Crash!
WAT ?!
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a]; // Crash!
[nil stringByAppendingString:@"b"]; [@"b" stringByAppendingString: nil];
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a]; // Crash!
[nil stringByAppendingString:@"b"]; // Error [@"b" stringByAppendingString: nil];
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a]; // Crash!
[nil stringByAppendingString:@"b"]; // Error [@"b" stringByAppendingString: nil]; // Warning //stringByAppendingString:(nonnull NSString *)
NSString *a; [a stringByAppendingString:@"b"]; // Nothing [@"b" stringByAppendingString:a]; // Crash!
[nil stringByAppendingString:@"b"]; // Error [@"b" stringByAppendingString: nil]; // Warning //stringByAppendingString:(nonnull NSString *) [(id)nil stringByAppendingString:a]; // !
!"
let a = "a" a + "b" /* ! */
"b" + a /* ! */
let a = "a" let a: String? a + "b"
/* ! */ a + "b" // Error "b" + a /* ! */ "b" + a // Error
let a: String? a + "b" // Error "b" +
a // Error if let a = a { a + "b" // ! }
let a: String? a + "b" // Error "b" +
a // Error a.stringByAppendingString("b") // Error if let a = a { a + "b" // ! } a?.stringByAppendingString("b") // !
typedef NS_ENUM(NSInteger, Action) { ActionDelete, ActionCreate, ActionEdit, ActionCopy };
typedef NS_ENUM(NSInteger, Action) { ActionDelete, ActionCreate, ActionEdit, ActionCopy }; //+
(void)runAction:(Action)action; [Runner runAction:ActionCreate];
typedef NS_ENUM(NSInteger, Action) { ActionDelete, ActionCreate, ActionEdit, ActionCopy }; //+
(void)runAction:(Action)action; [Runner runAction:ActionCreate]; [Runner runAction:20]; // WAT ?!
typedef NS_ENUM(NSInteger, Action) { ActionDelete, ActionCreate, ActionEdit, ActionCopy }; //+
(void)runAction:(Action)action; [Runner runAction:ActionCreate]; [Runner runAction:20]; // WAT ?! // !"# Action action = ActionEdit; action += ActionCopy; action /= 56; [Runner runAction:action];
+ (NSString *)actionString:(Action)action { switch (action) { case ActionDelete: return
@"Delete"; case ActionCreate: return @"Create"; case ActionEdit: return @"Edit"; case ActionCopy: return @"Copy"; } }
Swift enum Action { case Delete case Create case Edit
case Copy }
enum Action { case Delete case Create case Edit case
Copy } runAction(.Delete) //runAction(10) // Error!!
enum Action: String { case Delete case Create case Edit
case Copy } let action = Action.Delete.rawValue // Delete
enum Action: String { case Delete case Create case Edit
case Copy var isDangerous: Bool { return self == .Delete } } let danger = Action.Delete.isDangerous // true
- (void)setup { [self setupWithName:[App name]]; } - (void)setupWithName:(NSString *)name
{ [self setupWithName:name mode:ModeSqlite]; } - (void)setupWithName:(NSString *)name mode:(Mode)mode { [self setupWithName:name mode:ModeSqlite logeLevel:LogLevelVerbose]; } - (void)setupWithName:(NSString *)name mode:(Mode)mode logeLevel:(LogLevel)logLevel { ... } CoreDataStack *stack; [stack setup]; [stack setupWithName:@"Data" mode:ModeInMemory]; [stack setupWithName:@"Data" mode:ModeInMemory logeLevel:LogLevelNone]; //[stack logeLevel:LogLevelNone]; Error
Swift - Parameters default values func setup(name: String = App.name,
mode: Mode = .Sqlite, logLevel: LogLevel = .Verbose) { ... } let stack = CoreDataStack() stack.setup() stack.setup(logLevel: .None) stack.setup(mode: .InMemory, logLevel: .None) stack.setup("DB", mode: .InMemory, logLevel: .None)
"Is Swift ready for production?"
"Is Objective-C dying?" !
Q & A