Wednesday, 8 April 2015

Apple claims that Swift is 3.9x faster then Python.

Apple claims that Swift is 3.9x faster then Python. I’ve run some tests to check if it’s true.
I wrote the same QuickSort algorithm in C++, Swift and Python and then I run it for 100000 element random array on Core 2 Duo iMac. The results are
– 0.287s in c++
– 1.448s in Python
– 40.856s in Swift
I’m a little bit less in love after this tests.
[UPDATE]
It seems that Xcode can’t compile software or I don’t know how to use it. I’ve done the same test for 1000000 element array but without printing the result and I compiled it in terminal with -Ofast flag. Here is what I’ve got:
– 0.409s in C++
– 1.460s in Python
– 0.412s in Swift
So now I can be in love with Swift once again. Apple was actually right claiming that it is about 4x faster then Python.

Shortcut for Xcode

To help you get started, here’s a handy chart with some of the most commonly used editing and navigation keys:
Arrow Keys  Move cursor left/right/up/down
Control+F  Move cursor right one character, same as right arrow
Control+B  Move cursor left one character, same as left arrow
Control+N  Move cursor to end of next line, same as down arrow
Control+P  Move cursor to end of prior line, same as up arrow
Control+D  Delete the character under the cursor
Option+Left  Move cursor to start of prior word
Option+Right Move cursor to start of next word
Control+A  Move cursor to start of current line
Control+E  Move cursor to end of current line
Delete   Delete the character to the left of the cursor
Esc <   Move cursor to start of first line
Esc >   Move cursor to end of last line

Swift Style Guide


This style guide is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our books, tutorials, and starter kits nice and consistent — even though we have many different authors working on the books.
Our overarching goals are conciseness, readability, and simplicity.
Writing Objective-C? Check out our Objective-C Style Guide too.

Table of Contents

Naming

Use descriptive names with camel case for classes, methods, variables, etc. Class names and constants in module scope should be capitalized, while method names and variables should start with a lower case letter.
Preferred:
let MaximumWidgetCount = 100

class WidgetContainer {
  var widgetButton: UIButton
  let widgetHeightPercentage = 0.85
}
Not Preferred:
let MAX_WIDGET_COUNT = 100

class app_widgetContainer {
  var wBut: UIButton
  let wHeightPct = 0.85
}
For functions and init methods, prefer named parameters for all arguments unless the context is very clear. Include external parameter names if it makes function calls more readable.
func dateFromString(dateString: NSString) -> NSDate
func convertPointAt(#column: Int, #row: Int) -> CGPoint
func timedAction(#delay: NSTimeInterval, perform action: SKAction) -> SKAction!

// would be called like this:
dateFromString("2014-03-14")
convertPointAt(column: 42, row: 13)
timedAction(delay: 1.0, perform: someOtherAction)
For methods, follow the standard Apple convention of referring to the first parameter in the method name:
class Guideline {
  func combineWithString(incoming: String, options: Dictionary?) { ... }
  func upvoteBy(amount: Int) { ... }
}
When referring to functions in prose (tutorials, books, comments) include the required parameter names from the caller’s perspective. If the context is clear and the exact signature is not important, you can use just the method name.
Call convertPointAt(column:row:) from your own initimplementation.
If you implement timedAction, remember to provide an appropriate delay value.
You shouldn’t call the data source methodtableView(_:cellForRowAtIndexPath:) directly.
When in doubt, look at how Xcode lists the method in the jump bar – our style here matches that.
Methods in Xcode jump bar

Class Prefixes

Swift types are all automatically namespaced by the module that contains them. As a result, prefixes are not required in order to minimize naming collisions. If two names from different modules collide you can disambiguate by prefixing the type name with the module name:
import MyModule

var myClass = MyModule.MyClass()
You should not add prefixes to your Swift types.
If you need to expose a Swift type for use within Objective-C you can provide a suitable prefix (following our Objective-C style guide) as follows:
@objc (RWTChicken) class Chicken {
   ...
}

Spacing

  • Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode as shown below:Xcode indent settings
  • Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
  • Tip: You can re-indent by selecting some code (or ⌘A to select all) and then Control-I (or Editor\Structure\Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
Preferred:
if user.isHappy {
  //Do something
} else {
  //Do something else
}
Not Preferred:
if user.isHappy
{
    //Do something
}
else {
    //Do something else
}
  • There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.

Comments

When they are needed, use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.
Avoid block comments inline with code, as the code should be as self-documenting as possible.Exception: This does not apply to those comments used to generate documentation.

Classes and Structures

Which one to use?

Remember, structs have value semantics. Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn’t matter whether you use the first array or the second, because they represent the exact same thing. That’s why arrays are structs.
Classes have reference semantics. Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn’t mean they are the same person. But the person’s birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn’t have an identity.
Sometimes, things should be structs but need to conform to AnyObject or are historically modeled as classes already (NSDateNSSet). Try to follow these guidelines as closely as possible.

Example definition

Here’s an example of a well-styled class definition:
class Circle: Shape {
  var x: Int, y: Int
  var radius: Double
  var diameter: Double {
    get {
      return radius * 2
    }
    set {
      radius = newValue / 2
    }
  }

  init(x: Int, y: Int, radius: Double) {
    self.x = x
    self.y = y
    self.radius = radius
  }

  convenience init(x: Int, y: Int, diameter: Double) {
    self.init(x: x, y: y, radius: diameter / 2)
  }

  func describe() -> String {
    return "I am a circle at \(centerString()) with an area of \(computeArea())"
  }

  override func computeArea() -> Double {
    return M_PI * radius * radius
  }

  private func centerString() -> String {
    return "(\(x),\(y))"
  }
}
The example above demonstrates the following style guidelines:
  • Specify types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g. x: Int, and Circle: Shape.
  • Define multiple variables and structures on a single line if they share a common purpose / context.
  • Indent getter and setter definitions and property observers.
  • Don’t add modifiers such as internal when they’re already the default. Similarly, don’t repeat the access modifier when overriding a method.

Use of Self

For conciseness, avoid using self since Swift does not require it to access an object’s properties or invoke its methods.
Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions (as required by the compiler):
class BoardLocation {
  let row: Int, column: Int

  init(row: Int,column: Int) {
    self.row = row
    self.column = column

    let closure = { () -> () in
      println(self.row)
    }
  }
}

Protocol Conformance

When adding protocol conformance to a class, prefer adding a separate class extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Also, don’t forget the // MARK comment to keep things well-organized!
Preferred:
class MyViewcontroller: UIViewController {
  // class stuff here
}

// MARK: - UITableViewDataSource
extension MyViewcontroller: UITableViewDataSource {
  // table view data source methods
}

// MARK: - UIScrollViewDelegate
extension MyViewcontroller: UIScrollViewDelegate {
  // scroll view delegate methods
}
Not Preferred:
class MyViewcontroller: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
  // all methods
}

Function Declarations

Keep short function declarations on one line including the opening brace:
func reticulateSplines(spline: [Double]) -> Bool {
  // reticulate code goes here
}
For functions with long signatures, add line breaks at appropriate points and add an extra indent on subsequent lines:
func reticulateSplines(spline: [Double], adjustmentFactor: Double,
    translateConstant: Int, comment: String) -> Bool {
  // reticulate code goes here
}

Closure Expressions

Use trailing closure syntax wherever possible. In all cases, give the closure parameters descriptive names:
return SKAction.customActionWithDuration(effect.duration) { node, elapsedTime in 
  // more code goes here
}
For single-expression closures where the context is clear, use implicit returns:
attendeeList.sort { a, b in
  a > b
}

Types

Always use Swift’s native types when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.
Preferred:
let width = 120.0                                    //Double
let widthString = (width as NSNumber).stringValue    //String
Not Preferred:
let width: NSNumber = 120.0                                 //NSNumber
let widthString: NSString = width.stringValue               //NSString
In Sprite Kit code, use CGFloat if it makes the code more succinct by avoiding too many conversions.

Constants

Constants are defined using the let keyword, and variables with the var keyword. Any value thatis a constant must be defined appropriately, using the let keyword. As a result, you will likely find yourself using let far more than var.
Tip: One technique that might help meet this standard is to define everything as a constant and only change it to a variable when the compiler complains!

Optionals

Declare variables and function return types as optional with ? where a nil value is acceptable.
Use implicitly unwrapped types declared with ! only for instance variables that you know will be initialized later before use, such as subviews that will be set up in viewDidLoad.
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
self.textContainer?.textLabel?.setNeedsDisplay()
Use optional binding when it’s more convenient to unwrap once and perform multiple operations:
if let textContainer = self.textContainer {
  // do many things with textContainer
}
When naming optional variables and properties, avoid naming them like optionalStringormaybeView since their optional-ness is already in the type declaration.
For optional binding, shadow the original name when appropriate rather than using names likeunwrappedView or actualLabel.
Preferred:
var subview: UIView?

// later on...
if let subview = subview {
  // do something with unwrapped subview
}
Not Preferred:
var optionalSubview: UIView?

if let unwrappedSubview = optionalSubview {
  // do something with unwrappedSubview
}

Struct Initializers

Use the native Swift struct initializers rather than the legacy CGGeometry constructors.
Preferred:
let bounds = CGRect(x: 40, y: 20, width: 120, height: 80)
var centerPoint = CGPoint(x: 96, y: 42)
Not Preferred:
let bounds = CGRectMake(40, 20, 120, 80)
var centerPoint = CGPointMake(96, 42)
Prefer the struct-scope constants CGRect.infiniteRectCGRect.nullRect, etc. over global constants CGRectInfiniteCGRectNull, etc. For existing variables, you can use the shorter.zeroRect.

Type Inference

The Swift compiler is able to infer the type of variables and constants. You can provide an explicit type via a type alias (which is indicated by the type after the colon), but in the majority of cases this is not necessary.
Prefer compact code and let the compiler infer the type for a constant or variable.
Preferred:
let message = "Click the button"
var currentBounds = computeViewBounds()
Not Preferred:
let message: String = "Click the button"
var currentBounds: CGRect = computeViewBounds()
NOTE: Following this guideline means picking descriptive names is even more important than before.

Syntactic Sugar

Prefer the shortcut versions of type declarations over the full generics syntax.
Preferred:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?
Not Preferred:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>

Control Flow

Prefer the for-in style of for loop over the for-condition-increment style.
Preferred:
for _ in 0..<3 {
  println("Hello three times")
}

for (index, person) in enumerate(attendeeList) {
  println("\(person) is at position #\(index)")
}
Not Preferred:
for var i = 0; i < 3; i++ {
  println("Hello three times")
}

for var i = 0; i < attendeeList.count; i++ {
  let person = attendeeList[i]
  println("\(person) is at position #\(i)")
}

Semicolons

Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
Do not write multiple statements on a single line separated with semicolons.
The only exception to this rule is the for-conditional-increment construct, which requires semicolons. However, alternative for-in constructs should be used where possible.
Preferred:
var swift = "not a scripting language"
Not Preferred:
var swift = "not a scripting language";
NOTE: Swift is very different to JavaScript, where omitting semicolons is generally considered unsafe

Language

Use US English spelling to match Apple’s API.
Preferred:
var color = "red"
Not Preferred:
var colour = "red"

Smiley Face

Smiley faces are a very prominent style feature of the raywenderlich.com site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The closing square bracket ] is used because it represents the largest smile able to be captured using ASCII art. A closing parenthesis ) creates a half-hearted smile, and thus is not preferred.
Preferred:
:]
Not Preferred:
:)

Swift Quick reference

Swift the latest programming language released by Apple for developing OS X and iOS apps.
  • Best of C and Objective-C
  • Adopts safe programming patterns and modern features
  • Supports playground, a tool for seeing the result immediately.
  • Provides access to Cocoa libraries and can work in conjunction with Objective-C
  • Combines Procedural and Object-Oriented programming.
  • No need use semicolon at the end of statement. Use it only when you have more than one statement in single line.
  • Swift uses var and let. only mutable needs to be used var. Safe Modern, Power. Swift uses type inference. Use unicode character for name.
  • Prefers usage of constant (let) for immutable than using var.
  • You can use any character as variable.
  • Optional variables can contain value or nil. – var givenName : String? = “Ravi
  • Switch supports all kinds of datatype and operations and does need to add break after each case statement.
  • No need to enclose your expression in brackets with if statements
  • Swift function supports default value for the parameter and variable parameter.
  • Closures are like blocks in Objective-C ( ) -> ( )
  • No need to specify header file in Swift
  • No need to specify base class and there is no universal base class
  • No difference between instance variable and properties
  • Tuples – Grouping of multiple values.
  • Nested multiline comments are allowed.
  • Use typealias to provide different name to an existing type.
  • Swift nil represents absence of value and objective – C nil represents pointer to a non-existent object.
  • Implicitly unwrapped optional let pincode : String! = “E151EH”
  • Provides Assertion to end code execution where certain criteria is not met.
  • Swift’s String is value type and not passed by reference.
  • Optional Bindings
Variables and Constants
var myStr = “Swift”
let message = “Hello World”
let myValue = 23.1 (Implicit variable declaration)
let myDoubleValue: Double = 23 (Explicit variable declaration)
let myAge = 38
let message = “My age is “ + String(myAge) (Converting value to a String)
let newMessage = “My age is \(myAge) (Converting value to a String using backslash)
Data types in Swift
String
Int (Range -2,147,483,648 to 2,147,483,648)
Double (15 digit precision)
Float (6 digit precision)
Bool
Assignment Operator
  • a = b
  • let (a,b) = (2,3) – supports tuple.
  • Does not return value.
Arithmetic Operators
  • Addition (+), Subtraction (-), Multiplication (*), Division (/)
  • + can be used for string concatenation.
  • % – Returns remainder for both +ve and -ve numbers. Also returns remainder for floating point numbers.
  • Increment and Decrement operators, ++i (i = i + 1), —i (i = i – 1).
  • Supports i++ and i— (increments or decrements after returning the value).
  • Unary Minus and Unary Plus
Compound Assignment Operator
  • x += 2 is same as x = x + 2.
Comparison Operators
  • x == y
  • x != y
  • x > y
  • x < y
  • x >= y
  • x <= y
  • === and !== used for testing object references.
Ternary Conditional Operator
  • a = flag ? 10 : 20 (if flag is true then a will updated to 10 and 20 incase it is false).
Range Operators
  • Closed Range – e.g.:- 1…10, has three dots and includes values from 1 to 10.
  • Half Closed – e.g.:- 1..10, has two dots and includes values from 1 to 9
Logical Operators
  • NOT ( !x )
  • AND ( x && y )
  • OR ( x || y )
Collection Types
Array
var fruits = [“Apples”, “Oranges”, “Grapes”]
fruits[1] = “Pine Apples”
strArray.isEmpty //check if array is empty
strArray.append(”!”) //insert element at end of array
strArray += (”!”) //insert element at end of array
strArray = [] //empty
var addArrays = strArray + strNames //Add two arrays
var strNames:Character[] = Character[](count:2,repeatedValue:“a”) //Array with pre-defined size and default values
strArray.insert(”!”, atIndex: 0) //insert element at specified index
strArray.removeAtIndex(0) //remove element at specified index
strArray.removeLast() //remove last element
Dictionary
var expEmployees:Dictionary<Int,String> = [1:“Ravi”, 2:“Rajesh”] //Explicitly specify the type for key and value
var employees = [1:“Ravi”, 2:“Rajesh”] // Infer type of Keys and values
employees[“John”] = “Web Developer” // Add another element to the dictionary
employees.updateValue(“Rakesh”, forKey:1) // Update a value using key.
employees.removeAll(keepCapacity: false) //remove elements
employees.removeValueForKey(1) //remove value based on key
employees = [:] //make it empty
for (no,name) in employees {
}
for (no) in employees.keys {
}
for (name) in employees.values {
}
Control Flow
if salary {} incorrect, if salary > 40000 correct, expression should return a boolean value.
for statement with and without upper value
for i in 0..3 denotes that i does not include upper value 3.
for i in 0…3 denotes that i includes upper value
Comments
Single line comments // examples
Multiline comments /* example1
example2 */
Function
func <function_name> (<argument>:<argument_type) -> <return parameter> {
}
func sum(number1:Int, number2: Int) -> (Int) {
return number1 + number2
}
The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this.
func sum() -> (Int) {
return 10 + 5
}
The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this. Swift function can also have multiple return values.
Define external parameter name
func sum(addNumber1 number1:Int, withNumber2 number2: Int) -> (Int) {
return number1 + number2
}
println(sum(addNumber1: 10, withNumber2: 20))
Define addNumber1 and withNumber are external parameter names for two parameters. Use # to tell local and external parameter name are same.
func sum(#number1:Int, #withnumber2: Int) -> (Int) {
return number1 + withnumber2
}
println(sum(number1: 10, withnumber2: 20))
Function with default parameter value
func sum(number1:Int, withnumber2: Int = 20) -> (Int) {
return number1 + withnumber2
}
println(sum(10))
The above function has default value for the second parameter.
Variadic Parameters
A function with variadic parameters can accept zero or more values. Maximum of one parameter is allowed in a function and it is always last in the list.
Variable and inout parameters
Variable parameters in a function are indicated by var keyword and the scope is available only within the function. If you want to access the modified variable value outside the function then you specify them as inout parameter. And prefix with & while passing the parameter in the function call.