This document compares Objective-C and Swift programming languages. It discusses their differences in data types, defining new data types, extending existing data types, properties, methods, closures, generics, operators, C bridging, and performance based on fibonacci and sum tests.
24. 24
Data
Types
Objective
C Swift
NSInteger Int
double Double
BOOL Bool
NSString String
NSArray Array
id AnyObject
Class AnyClass
SEL Selector
25. 25
Define
new
Data
Types
Objective
C Swift
@interface class
@protocol protocol
struct struct
enum enum
26. 26
Extending
existing
Data
Types
Objective
C Swift
categories extension
@interface (categoryName)
@end
class a{
}
extension a {
}
struct b {
}
extension b{
}
enum b {
}
extension b{
}
27. 27
#if __LP64__
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
!
#define NSIntegerMax LONG_MAX
#define NSIntegerMin LONG_MIN
#define NSUIntegerMax ULONG_MAX
Objective-C
Data type definitions
28. 28
struct Int : SignedInteger {
init()
init(_ value: Int)
....
static var max: Int { get }
static var min: Int { get }
}
!
extension Int : Printable {
var description: String { get }
}
Swift
Data type definitions
29. 29
@property (nonatomic) NSMutableArray *items;
@property (nonatomic, strong) NSArray *immutableItems;
@property (nonatomic, weak) id<DelegateProtocol> delegate;
Objective-C
var items:Array<Int> = []
let immutableItems = [1, 2, 3, 4]
weak var delegate:DelegateProtocol?
Swift
Properties
35. 35
// UIView.swift
class func animateWithDuration(duration: NSTimeInterval,
animations: (() -> Void)!)
!
//Usage
UIView.animateWithDuration(2.5) {
....
}
Swift
Closures
36. 36
NSArray *arrayOfStrings = @[@"First", @"Second", @2, @"Third"];
Objective-C
var array:Array<Strings> = ["First", "Second", 2, "Third"]
Swift
Generics
37. 37
operator infix ^ {}
func ^ (var base: Int, power: Int) -> Int {
var answer = 1;
for _ in 1...power {
answer = answer * base
}
return answer
}
var x = 2^5 // x = 32
Swift
Defining operators
38. 38
// C Functions
func arc4random() -> UInt32
!
// Core Graphics Classes
func CGGradientCreateWithColorComponents(
space: CGColorSpace!,
components: ConstUnsafePointer<CGFloat>,
locations: ConstUnsafePointer<CGFloat>,
count: UInt) -> CGGradient!
Swift
C Bridging