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
余白を設計しフロントエンド開発を 加速させる
tsukuha
7
2.1k
izumin5210のプロポーザルのネタ探し #tskaigi_msup
izumin5210
1
130
Unicodeどうしてる? PHPから見たUnicode対応と他言語での対応についてのお伺い
youkidearitai
PRO
1
2.6k
Patterns of Patterns
denyspoltorak
0
1.4k
CSC307 Lecture 09
javiergs
PRO
1
840
24時間止められないシステムを守る-医療ITにおけるランサムウェア対策の実際
koukimiura
1
100
OCaml 5でモダンな並列プログラミングを Enjoyしよう!
haochenx
0
140
コントリビューターによるDenoのすゝめ / Deno Recommendations by a Contributor
petamoriken
0
200
AtCoder Conference 2025
shindannin
0
1.1k
カスタマーサクセス業務を変革したヘルススコアの実現と学び
_hummer0724
0
720
15年続くIoTサービスのSREエンジニアが挑む分散トレーシング導入
melonps
2
220
並行開発のためのコードレビュー
miyukiw
0
280
Featured
See All Featured
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.3k
The Limits of Empathy - UXLibs8
cassininazir
1
220
Lightning talk: Run Django tests with GitHub Actions
sabderemane
0
120
How STYLIGHT went responsive
nonsquared
100
6k
Are puppies a ranking factor?
jonoalderson
1
2.7k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.4k
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
3.6k
For a Future-Friendly Web
brad_frost
182
10k
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
270
Ethics towards AI in product and experience design
skipperchong
2
200
Build The Right Thing And Hit Your Dates
maggiecrowley
39
3k
Mind Mapping
helmedeiros
PRO
0
88
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 !