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
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
Lambda のコードストレージ容量に気をつけましょう
tattwan718
0
130
プロダクトオーナーから見たSOC2 _SOC2ゆるミートアップ#2
kekekenta
0
220
コマンドとリード間の連携に対する脅威分析フレームワーク
pandayumi
1
460
Fluid Templating in TYPO3 14
s2b
0
130
【卒業研究】会話ログ分析によるユーザーごとの関心に応じた話題提案手法
momok47
0
200
Unicodeどうしてる? PHPから見たUnicode対応と他言語での対応についてのお伺い
youkidearitai
PRO
1
2.6k
15年続くIoTサービスのSREエンジニアが挑む分散トレーシング導入
melonps
2
220
ぼくの開発環境2026
yuzneri
0
240
AIによるイベントストーミング図からのコード生成 / AI-powered code generation from Event Storming diagrams
nrslib
2
1.9k
[KNOTS 2026登壇資料]AIで拡張‧交差する プロダクト開発のプロセス および携わるメンバーの役割
hisatake
0
290
「ブロックテーマでは再現できない」は本当か?
inc2734
0
1k
360° Signals in Angular: Signal Forms with SignalStore & Resources @ngLondon 01/2026
manfredsteyer
PRO
0
130
Featured
See All Featured
Technical Leadership for Architectural Decision Making
baasie
2
250
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.7k
The Curious Case for Waylosing
cassininazir
0
240
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
5.2k
Optimizing for Happiness
mojombo
379
71k
Discover your Explorer Soul
emna__ayadi
2
1.1k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
220
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
78
Design in an AI World
tapps
0
140
Are puppies a ranking factor?
jonoalderson
1
2.7k
Leading Effective Engineering Teams in the AI Era
addyosmani
9
1.6k
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
3.6k
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 !