- The Basics
- Types 1. Converting types 2. Cast 3. Var & constants
- Dictionary
- The typeof statement
- Tuples
- Enumerations
- Declaring constants and variables
- Optional
- Swift Documentation
- Memory
- The guard statement
- Variable property attributes or Modifiers in iOS
- Control flow
- The if statement
- The for loop
- The while loop
- The switch statement
- The guard statement
- Functions
- Selector
- Closures
- Classes
- Class prefix
- Initializers 1. Designated initializers 2. Convenience initializers
- Modifiers for methods
- Properties 1. Stored Property 2. Computed Property
- Generic
- Protocols
- Associated types
- Extension - Categories
- Handling Errors
- Testing
- Properties
- Stored Properties
- Lazy Stored Properties
- Computed Properties
- IBAction and IBOutlet
- References
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"
Convert | Swift | Objective-C |
---|---|---|
String to Int | let intValue = Int("79") | |
Int to String | let stringValue = "(intValue)" |
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! |
// var
var fooBool : Bool = true
// constants
var myDictionary = [String : String] = [:]
__weak typeof(self) this = self;
var myClosure = {
[unowned self] in
print(self.description)
}
let city = (91, "Madrid")
let city2 = (prefixPhone: 91, name: "Madrid")
enum Enumerations {
case value1
case value2
case value3, value4
func method() -> String {
return "return value"
}
}
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 variables and constants are defined using ? (question mark).
/**
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
Modifier | Swift | Objective-C |
---|---|---|
atomic | ||
nonatomic | ||
strong=retain | ||
weak= unsafe_unretained | ||
retain | ||
assign | ||
unsafe_unretained | ||
copy | ||
readonly | ||
readwrite |
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 {
}
for i in 0...5 {
}
for _ in 0...5 {
}
for i in 0..<5 {
}
guard let x > 10 else {
print "error"
}
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 {
}
func callMethod {
}
#selector(callMethod)
// file.m
- (void) callMehod {
}
@selector(callMethod:)
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"];
}
class ClassName : superClass {
}
// file.h
@interface ClassName : superClass
@end
// implementation_file.m
@interface ClassName ()
@end
@implementation ClassName
@end
You do not need class prefixes in Swift, because classes are namespaced to the module in which they live. Reference: stackoverflow,developer.apple.com
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
}
}
}
class TheClass {
init() {
}
}
class TheClass {
convenience init() {
}
}
Modifier | Swift | Objective-C |
---|---|---|
static | subclasses can override class methods | |
class | subclasses cannot override static methods | |
override |
// ExampleClass.h
// ExampleClass.m
@interface ExampleClass ()
@property (nonatomic, strong) String *exampleName;
@end
@implementation VTDAppDependencies
// ...
@end
let pi = 3.1415
let name: String {
get {
return "value"
}
set(value) {
}
}
class Entity {
}
class ClassName <T: Entity> : superClass {
}
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
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)
}
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
func methodA() throws -> String {
return "swift"
}
func methodB() {
do {
try methodA()
} catch {
print("error")
}
}
@try {
[methodWithThrows];
} @catch (NSException *e) {
NSLog(@"error");
} @finally {
}
Swift | Objective-C |
---|---|
Quick/Nimble | Specta/Expecta |
Kiwi |
struct MyStruct {
var variableStoredProperties: Int
let constantStoredProperties: Int
}
struct MyStruct {
lazy var variableStoredProperties = String()
}
struct MyStruct {
var variableComputedProperties : String {
get {
return "value"
}
}
}
Swift | Objective-C |
---|---|
@IBOutlet var tabBarButtons: Array! | @property (nonatomic, strong) IBOutletCollection(UIButton) NSArray *tabBarButtons; |
@IBOutlet var tabBarButton: UIButton! | @property (nonatomic, strong) IBOutlet UIButton *tabBarButton; |
David Marín,
ObjectiveC_vs_Swift.doc is available under the MIT license. See the LICENSE file for more info.