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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
なぜSQLはAIぽく見えるのか/why does SQL look AI like
florets1
0
470
FOSDEM 2026: STUNMESH-go: Building P2P WireGuard Mesh Without Self-Hosted Infrastructure
tjjh89017
0
170
AI Schema Enrichment for your Oracle AI Database
thatjeffsmith
0
310
HTTPプロトコル正しく理解していますか? 〜かわいい猫と共に学ぼう。ฅ^•ω•^ฅ ニャ〜
hekuchan
2
690
並行開発のためのコードレビュー
miyukiw
0
290
AI & Enginnering
codelynx
0
120
インターン生でもAuth0で認証基盤刷新が出来るのか
taku271
0
190
Vibe Coding - AI 驅動的軟體開發
mickyp100
0
180
CSC307 Lecture 08
javiergs
PRO
0
670
izumin5210のプロポーザルのネタ探し #tskaigi_msup
izumin5210
1
130
Architectural Extensions
denyspoltorak
0
290
CSC307 Lecture 05
javiergs
PRO
0
500
Featured
See All Featured
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
0
140
How to Grow Your eCommerce with AI & Automation
katarinadahlin
PRO
1
110
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.3k
Navigating the moral maze — ethical principles for Al-driven product design
skipperchong
2
250
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
196
71k
Practical Orchestrator
shlominoach
191
11k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
330
Bash Introduction
62gerente
615
210k
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
170
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.2k
Prompt Engineering for Job Search
mfonobong
0
160
Reality Check: Gamification 10 Years Later
codingconduct
0
2k
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 !