$30 off During Our Annual Pro Sale. View Details »
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Converting Objective-C to Swift
Search
David Kobilnyk
August 14, 2014
Programming
1
16k
Converting Objective-C to Swift
Learn about a lot of issues encountered when converting code to Swift, and about Swift in general.
David Kobilnyk
August 14, 2014
Tweet
Share
Other Decks in Programming
See All in Programming
20251127_ぼっちのための懇親会対策会議
kokamoto01_metaps
2
370
ソフトウェア設計の課題・原則・実践技法
masuda220
PRO
24
20k
【レイトレ合宿11】kagayaki_v4
runningoutrate
0
200
レイトレZ世代に捧ぐ、今からレイトレを始めるための小径
ichi_raven
0
490
分散DBって何者なんだ... Spannerから学ぶRDBとの違い
iwashi623
0
160
Atomics APIを知る / Understanding Atomics API
ssssota
1
240
モデル駆動設計をやってみよう Modeling Forum2025ワークショップ/Let’s Try Model-Driven Design
haru860
0
210
GeistFabrik and AI-augmented software development
adewale
PRO
0
230
モダンJSフレームワークのビルドプロセス 〜なぜReactは503行、Svelteは12行なのか〜
fuuki12
0
160
TypeScript 5.9 で使えるようになった import defer でパフォーマンス最適化を実現する
bicstone
1
590
目的で駆動する、AI時代のアーキテクチャ設計 / purpose-driven-architecture
minodriven
11
3.8k
無秩序からの脱却 / Emergence from chaos
nrslib
2
11k
Featured
See All Featured
Optimising Largest Contentful Paint
csswizardry
37
3.5k
Build your cross-platform service in a week with App Engine
jlugia
234
18k
Scaling GitHub
holman
464
140k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.3k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
231
22k
Intergalactic Javascript Robots from Outer Space
tanoku
273
27k
4 Signs Your Business is Dying
shpigford
186
22k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
17k
BBQ
matthewcrist
89
9.9k
Facilitating Awesome Meetings
lara
57
6.6k
Navigating Team Friction
lara
191
16k
The Cost Of JavaScript in 2023
addyosmani
55
9.3k
Transcript
Converting Objective-C to Swift David Kobilnyk
Swift Types Value Types Reference Types Enums Structs Classes Int
Float Array Dictionary String Bool Double
Value Types
Using Enums Objective-C: UIControlStateNormal ! Swift: UIControlState.Normal or just .Normal
Using Enums [self.tableView insertRowsAtIndexPaths: @[indexPath] withRowAnimation: UITableViewRowAnimationAutomatic]; ! self.tableView.insertRowsAtIndexPaths( [indexPath],
withRowAnimation: .Automatic)
Initializing Structs ! CGPoint p = CGPointMake(12, 64); ! !
let p = CGPoint(x: 12, y: 64)
No Implicit Casting float red = (arc4random() % 100) /
100.0; ! ! let red = (arc4random() % 100) / 100.0 'UInt32' is not convertible to 'Int' ! let red = Float(arc4random() % 100) / 100.0 // Ok
Arrays ! NSArray *a = @[@"pale ale", @"stella"]; ! !
let a: [String] = ["pale ale", "stella"] // or let a = ["pale ale", "stella"]
Mutating an Array ! NSMutableArray *a = @[]; [a addObject:@"hefeweizen"];
! ! var a = [String]() a.append("hefeweizen") a += ["hefeweizen"]
Dictionaries ! NSMutableDictionary *ages = [NSMutableDictionary new]; ! ! var
ages: [String: Int] = [String: Int]() var ages = [String: Int]()
Dictionaries ages[@"Al"] = [NSNumber numberWithInt:35]; ages[@"Liz"] = [NSNumber numberWithInt:26]; !
ages["Al"] = 35 ages["Liz"] = 26
Iterating Dictionaries for (NSString *name in ages) { NSLog(@"%@ is
%@", name, [ages objectForKey:name]); } ! for (name, age) in ages { println("\(name) is \(age)") }
Value Type Mutability let a = [1, 2] a[0] =
5 '@lvalue $T5' is not identical to 'Int' ! var a = [1, 2] a[0] = 5 // no error
Using Classes
Mutability of Classes let str1 = NSMutableAttributedString(string:"yo") str1.appendAttributedString(str1) // no
error ! var str2 = NSAttributedString(string: "yo") str2.appendAttributedString(str2) ! 'NSAttributedString' does not have a member named 'appendAttributedString'
Mutability of Classes let str1 = NSMutableAttributedString(string: "yo") var str2
= NSAttributedString(string: "yo") ! str2 = str1 // no error str1 = str2 ! 'Cannot assign to 'let' value 'str1'
Class Initialization [UIColor colorWithRed:0.1 green:0.6 blue:0.3 alpha:1.0]; [[UIColor alloc] initWithRed:0.1
green:0.6 blue:0.3 alpha:1.0]; ! UIColor(red: 0.1, green: 0.6, blue: 0.3, alpha: 1.0)
Class-Level Usage ! [UITableViewCell class] ! ! UITableViewCell.self
Class-Level Usage [self.tableView registerClass: [UITableViewCell class] forCellReuseIdentifier:@"Cell"]; ! tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier:
"Cell")
Optionals
Nil let a: Int = nil Type 'Int' does not
conform to protocol 'NilLiteralConvertible' ! let b: Int? = nil // No error
Unwrapping Optionals let a: Int? = 10 println(a) // prints
"Optional(10)" println(a!) // prints "10" ! let b: Int? = nil println(b!) // fatal error: unexpectedly found nil while unwrapping an Optional value
Unwrapping Optionals var name: String? = "Al" if let unwrappedName
= name { println(unwrappedName) } else { println("name is nil") }
Unwrapping Optionals var name: String? = "Al" if let name
= name { // This is ok println(name) // Using unwrapped 'name' }
Mutating Optional Value Types if var unwrappedName = name {
unwrappedName.write("bert") // unwrappedName changes to "Albert" // name remains "Al" }
Mutating Optional Value Types var unwrappedName = name! unwrappedName.write("bert") //
name is still "Al" name!.write("bert") // force unwrap // name is now "Albert" name?.write("bert") // safe unwrap // name is now "Albertbert"
Mutating Optional Class Types let v: UIView? = UIView() if
let u = v { u.hidden = true } // v is updated as well
Mutating Optional Class Types let v: UIView? = UIView() let
u = v! u.hidden = true // v is updated as well
Checking for Nil var name: String? = "Al" if name
{ // causes error // … } Type 'String?' does not conform to protocol 'BooleanType.Protocol'
Checking for Nil var name: String? = "Al" if name
!= nil { // … } // No error
Checking for Nil var name: String? = "Al" if let
_ = name { // … } // No error
Building Classes
Class Declaration class Food { ! } ! let food
= Food()
Stored Properties class Food { var name: String } Class
'Food' has no initializers
Stored Properties class Food { var name: String init() {}
} Error: Property 'self.name' not initialized
Designated Inits class Food { var name: String init(name: String)
{ self.name = name } } var food = Food(name: "hard-boiled egg")
Default Values class Food { var name: String = "[Unnamed]"
} // No error !
Optional Properties class Food { var name: String? } //
No error !
Designated Inits class Food { var name: String init(name: String)
{ self.name = name } } var food = Food() !
Designated Inits class Food { var name: String init(name: String)
{ self.name = name } } var food = Food() Missing argument for parameter 'name' in call
Convenience Inits class Food { var name: String init(name: String)
{ self.name = name } convenience init() { self.init(name: "[Unnamed]") } }
Inits and Inheritance class RecipeIngredient: Food { ! } !
let ingredient = RecipeIngredient()
Inits and Inheritance class RecipeIngredient: Food { var quantity: Int
} Error: Class ‘RecipeIngredient’ has no initializers
Inits and Inheritance class RecipeIngredient: Food { var quantity: Int
init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } } // No error
Inits and Inheritance let ingredient = RecipeIngredient(name: "spinach")
Inits and Inheritance let ingredient = RecipeIngredient(name: "spinach") Missing argument
for parameter 'quantity' in call
Inits and Inheritance class RecipeIngredient: Food { var quantity: Int
init(name: String, quantity: Int) { … } override convenience init(name: String) { self.init(name: name, quantity: 1) } }
Init Code Conversion Example @interface BNRDrawView () <UIGestureRecognizerDelegate> ! @property
(nonatomic, strong) UIPanGestureRecognizer *moveRecognizer; ! @end
Init Code Conversion Example class BNRDrawView: UIView, UIGestureRecognizerDelegate { private
let moveRecognizer: UIPanGestureRecognizer }
Init Code Conversion Example @implementation BNRDrawView - (instancetype)initWithFrame:(CGRect)r { self
= [super initWithFrame:r]; if (self) { self.moveRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveLine:)]; [self addGestureRecognizer:self.moveRecognizer]; } return self; }
Init Code Conversion Example override init(frame: CGRect) { moveRecognizer =
UIPanGestureRecognizer(target: self, action: "moveLine:") addGestureRecognizer(moveRecognizer) super.init(frame: frame) }
Init Code Conversion Example override init(frame: CGRect) { moveRecognizer =
UIPanGestureRecognizer(target: self, action: "moveLine:") addGestureRecognizer(moveRecognizer) super.init(frame: frame) } 'self' used before super.init call
Init Code Conversion Example override init(frame: CGRect) { super.init(frame: frame)
moveRecognizer = UIPanGestureRecognizer(target: self, action: "moveLine:") addGestureRecognizer(moveRecognizer) } Property 'self.moveRecognizer' not initialized at super.init call
Init Code Conversion Example class BNRDrawView: UIView, UIGestureRecognizerDelegate { private
let moveRecognizer: UIPanGestureRecognizer! }
Init Code Conversion Example override init(frame: CGRect) { super.init(frame: frame)
moveRecognizer = UIPanGestureRecognizer(target: self, action: "moveLine:") addGestureRecognizer(moveRecognizer) } // No error
IBOutlets @property (nonatomic, weak) IBOutlet UIDatePicker *datePicker; ! @IBOutlet weak
var datePicker: UIDatePicker? @IBOutlet weak var datePicker: UIDatePicker!
Custom Setters @property (nonatomic, strong) BNRItem *containedItem; // … -
(void)setContainedItem:(BNRItem *)containedItem { _containedItem = containedItem; self.containedItem.container = self; }
Computed Properties var containedItem: BNRItem? { get { ! }
set { } }
willSet/didSet var containedItem: BNRItem? { didSet { if let containedItem
= containedItem { containedItem.container = self } } }
Privately Mutable Public Properties ! @interface BNRItemStore () @property (nonatomic,
readonly) NSArray *allItems; @end ! @interface BNRItemStore () @property (nonatomic) NSMutableArray *privateItems; @end
Privately Mutable Public Properties ! ! class BNRItemStore { private(set)
var allItems = [BNRItem]() }
More Information ! ! David Kobilnyk
[email protected]
github.com/davidkobilnyk/BNRGuideSolutionsInSwift !