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
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
590
CSC307 Lecture 06
javiergs
PRO
0
690
dchart: charts from deck markup
ajstarks
3
1k
CSC307 Lecture 02
javiergs
PRO
1
780
CSC307 Lecture 08
javiergs
PRO
0
670
それ、本当に安全? ファイルアップロードで見落としがちなセキュリティリスクと対策
penpeen
7
3.9k
【卒業研究】会話ログ分析によるユーザーごとの関心に応じた話題提案手法
momok47
0
200
LLM Observabilityによる 対話型音声AIアプリケーションの安定運用
gekko0114
2
430
360° Signals in Angular: Signal Forms with SignalStore & Resources @ngLondon 01/2026
manfredsteyer
PRO
0
130
生成AIを使ったコードレビューで定性的に品質カバー
chiilog
1
270
Data-Centric Kaggle
isax1015
2
780
「ブロックテーマでは再現できない」は本当か?
inc2734
0
1k
Featured
See All Featured
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
3.6k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
200
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
55
3.2k
Building a Scalable Design System with Sketch
lauravandoore
463
34k
WCS-LA-2024
lcolladotor
0
450
Principles of Awesome APIs and How to Build Them.
keavy
128
17k
Test your architecture with Archunit
thirion
1
2.2k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
508
140k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.2k
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
78
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 !