Skip to content

DavidMarinCalleja/swift-is-like-objective-c

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Objective-C vs Swift

Index

  1. The Basics
  2. Types 1. Converting types 2. Cast 3. Var & constants
  3. Dictionary
  4. The typeof statement
  5. Tuples
  6. Enumerations
  7. Declaring constants and variables
  8. Optional
  9. Swift Documentation
  10. Memory
  11. The guard statement
  12. Variable property attributes or Modifiers in iOS
  13. Control flow
  14. The if statement
  15. The for loop
  16. The while loop
  17. The switch statement
  18. The guard statement
  19. Functions
  20. Selector
  21. Closures
  22. Classes
  23. Class prefix
  24. Initializers 1. Designated initializers 2. Convenience initializers
  25. Modifiers for methods
  26. Properties 1. Stored Property 2. Computed Property
  27. Generic
  28. Protocols
  29. Associated types
  30. Extension - Categories
  31. Handling Errors
  32. Testing
  33. Properties
  34. Stored Properties
  35. Lazy Stored Properties
  36. Computed Properties
  37. IBAction and IBOutlet
  38. References

The Basics

Types

Swift Objective-C description
UInt8 uint8_t 0 ... 255
Int8 -128 ... 127
UInt16 0 ... 65,535
Int16 -32,768 ... 32,767
UInt32 uint32_t 0 ... 4,294,967,295
Int32 -2,147,483,648 ... 2,147,483,647
UInt64 uint64_t 0 ... 18,446,744,073,709,551,615
Int64 -9,223,372,036,854,775,808 ... 9,223,372,036,854,775,807
Int int
UInt
Double double
Float float
long
Bool BOOL true or false in Swift.
String NSString String
Character
Any Any can be utilized to all other types too, including struct and enum
AnyObject id AnyObject can only represent class type

dynamicType for display type

var fooString = "value"
print(fooString.dynamicType)
// "String\n"

Converting types

Convert Swift Objective-C
String to Int let intValue = Int("79")
Int to String let stringValue = "(intValue)"

Cast

Convert Swift Objective-C
explicit cast vehicle = car as Vehicle
check the “is-a sentence” car is Car
only performs the cast, if the cast is possible as?
you are very sure that the cast is possible as!

Type casting in swift

Var & constants

// var
var fooBool : Bool = true

// constants

Dictionary

var myDictionary = [String : String] = [:]

The typeof statement

__weak typeof(self) this = self;
var myClosure = {
    [unowned self] in
    print(self.description)
}

Tuples

let city = (91, "Madrid")
let city2 = (prefixPhone: 91, name: "Madrid")

Enumerations

enum Enumerations {
  case value1
  case value2
  case value3, value4

  func method() -> String {
    return "return value"
  }
}

Declaring constants and variables

Modifier Swift Objective-c
private details of a class hidden from the rest of the app
internal details of a framework hidden from the client app
public
Reference: Access Control and protected

Optional

Optional variables and constants are defined using ? (question mark).

Swift Documentation

/**
   Description

   # Lists
   You can apply *italic*, **bold**, or `code` inline styles.

   - parameter parameterName: parameter name
   - returns: return value
*/

Line separator code

// MARK: - DataSource
// TODO:
// FIXME

Memory

Variable property attributes or Modifiers in iOS

original link

Modifier Swift Objective-C
atomic
nonatomic
strong=retain
weak= unsafe_unretained
retain
assign
unsafe_unretained
copy
readonly
readwrite

Control flow

The if statement

let foo = 10
if foo == 10 {
  print("ok")
}

let poo = true
// == true is not necessary
if poo {

}

// ! not operator
if !poo {

} else {

}

// && AND
if foo == 10 && poo {

}

The for loop

for i in 0...5 {
}

for _ in 0...5 {
}

for i in 0..<5 {
}

The while loop

The switch statement

The guard statement

guard let x > 10 else {
   print "error"
}

Functions

func foo (parameterName : String) -> String {

}

// variable number of arguments
func foo2 (parameterName : String...) -> String {

}

// If you want to modify a parameter’s value, define that parameter as an in-out parameter instead
func foo3 (inout a:Int) {

}
// file.h
-(return_type) foo: (type) parameterName {

}

Selector

func callMethod {

}

#selector(callMethod)
// file.m
- (void) callMehod {

}

@selector(callMethod:)

Closures

let foo = {
  (bar: String) -> String in
  print("foo closures \(bar)")
  return "foo"
}
// file.m
NSString *(^foo)(NSString *) = ^(NSString bar) {
  NSLog(@"foo closures %@", bar);
  return [NSString stringWithFormat:@"foo"];
}

Classes

class ClassName : superClass {

}
// file.h
@interface ClassName : superClass

@end

// implementation_file.m
@interface ClassName ()

@end

@implementation ClassName

@end

Class prefix

You do not need class prefixes in Swift, because classes are namespaced to the module in which they live. Reference: stackoverflow,developer.apple.com

Initializers

class TheClass {
  init() {

  }
}
// file.h
@interface Foo : NSObject
-(instancetype) initWithName: (NSString* )name;
@end

// file.m
@implementation Foo
-(instancetype) initWithName: (NSString* )name {
  if (self = [super init]) {
    self._name = name;
  }
  return self;
}
@end

Starting in Xcode 6.1 beta 1, Swift initializers can be declared to return an optional:

class TheClass {
  init?(value:Int) {
    if value == 0 {
      return nil
    }
  }
}

Designated initializers

class TheClass {
  init() {

  }
}

Convenience initializers

class TheClass {
  convenience init() {

  }
}

Modifiers for methods

Modifier Swift Objective-C
static subclasses can override class methods
class subclasses cannot override static methods
override

Properties

// ExampleClass.h

// ExampleClass.m
@interface ExampleClass ()
@property (nonatomic, strong) String *exampleName;
@end

@implementation VTDAppDependencies
  // ...
@end

Stored Property

let pi = 3.1415

Computed Property

let name: String {
  get {
    return "value"
  }
  set(value) {

  }
}

Generic

class Entity {

}

class ClassName <T: Entity> : superClass {

}

Protocols

protocol ProtocolName {
static func protocolMethod()
}
// file.h
@protocol ProtocolName
- (void)protocolMethod;
@end

// otherFile.h
@interface otherFile : NSObject <ProtocolName>
- (void)otherFileMethod;
@end

// otherFile.m
@implementation otherFile

- (void)protocolMethod {
}

- (void)otherFileMethod {
}

@end

Associated types

Protocols in Swift cannot be defined generically using type parameters. Instead, protocols can define what are known as associated types using the typealias keyword.

// A protocol for things that can accept food.
protocol FoodEatingType {
  typealias Food

  var isSatiated : Bool { get }
  func feed(food: Food)
}

reference

Extension - Categories

extension ClassToExtend {
func instanceClassName()
}
// ClassName+categoryName.h
#import "ClassName.h"

@interface ClassName (categoryName)
-(void) instanceClassName();
@end

// ClassName+categoryName.m
@implementation ClassName (categoryName)

-(void) instanceClassName() {
}

@end

Handling Errors

func methodA() throws -> String {
  return "swift"
}

func methodB() {
  do {
    try methodA()
  } catch {
    print("error")
  }
}
@try {
  [methodWithThrows];
} @catch (NSException *e) {
  NSLog(@"error");
} @finally {

}

Testing

Swift Objective-C
Quick/Nimble Specta/Expecta
Kiwi

Properties

Stored Properties

struct MyStruct {
  var variableStoredProperties: Int
  let constantStoredProperties: Int
}

Lazy Stored Properties

struct MyStruct {
  lazy var variableStoredProperties = String()
}

Computed Properties

struct MyStruct {
  var variableComputedProperties : String {
      get {
          return "value"
      }
  }
}

IBAction and IBOutlet

Swift Objective-C
@IBOutlet var tabBarButtons: Array! @property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *tabBarButtons;
@IBOutlet var tabBarButton: UIButton! @property (nonatomic, strong) IBOutlet UIButton *tabBarButton;

References

Author

David Marín,

License

ObjectiveC_vs_Swift.doc is available under the MIT license. See the LICENSE file for more info.

About

Objective-C vs Swift Comparison

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published