StartwithSwift
SWIFT for beginners
Whatisswift????
Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC).
Swift is a powerful language that is easy to learn.
Swift adopts safe programming patterns and adds modern features to make programming easier, more
flexible, and more fun.
Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an
opportunity to reimagine how software development works.
It provides seamless access to existing Cocoa frameworks and mix-and-match interoperability with
Objective-C code
It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code
and see the results immediately, without the overhead of building and running an app.
Swiftfeatures
1.Safe:Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and
integers are checked for overflow, and memory is managed automatically. Another safety feature is that by default
Swift objects can never be nil.
2.Fast:Swift was built to be fast. Using the incredibly high-performance LLVM compiler, Swift code is
transformed into optimized native code that gets the most out of modern hardware.
3.Expressive: Expressive means that it’s easy to write code that’s easy to understand, both for the compiler
and for a human reader.
SimilaritiestoC
Most C operators are used in Swift, but there are some new operators.
Curly braces are used to group statements.
Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new identity operator,
===, is provided to check if two data elements refer to the same object.
Control statements while, if, and switch are similar, but have extended functions, e.g., a switch that takes non-integer
cases, while and if supporting pattern matching and conditionally unwrapping optionals, etc.
swiftvs.objectiveC
● Swift supports safe memory management, strong typing, generics and optionals, simple but strict inheritance
rules.
● Swift is cleaner and more readable than Objective-C. There are modules that eliminate class prefixes. It also has
half as many files in a project, and understandable closure syntax.
● Swift allows to create flexible and lightweight classes which contain exactly what you want.
● Swift is faster than Objective-C.
● Swift supports a limited operator overloading. Objective-C does not.
● Many things like structs, enums, and scalar types are first-class objects in Swift that are not objects in Objective-C
● Swift supports Tuples. Objective-C does not.
Swiftprogrammingfeatures
● Variables & Constants
● Optionals
● Control Flow
● Type Inference
● Tuples
● String Interpolation
● Functional Programming Patterns
● Enumerations
● Functions
Variables&constants
In Swift we use var and let keyword to declare a variables/constants.
var someVar = 100 // variable whose value can be updated
Var someStr = “Some String”
let const1 = 120 // constant whose value can not be changed
Let constSTr = “Constant String”
optionals
Optionals are not a part of Objective C. They allow functions which may not always be able to return a meaningful value (i.e.
a valid o/p) to return either a value encapsulated in an optional or nil. In C and Objective-C, we can already return nil from a
function that would normally return an object, but we don’t have this option for functions which are expected to return a
basic type such as int, float, or double. This is performed with the ! operator:
let result = anOptionalInstance!.someMethod()
In this case, the ! operator unwraps anOptionalInstance to expose the instance inside, allowing the method call to be made on it. If
anOptionalInstance is nil, a null-pointer error occurs.
let myValue = anOptionalInstance?.someMethod()
In this case the runtime only calls someMethod if anOptionalInstance is not nil, suppressing the error.
Controlflow
Anyone who’s programmed in C or a C-like language is familiar with the use of curly braces ({}) to delimit code blocks. In
Swift, however, they’re not just a good idea: they’re the law!
if someVar < 100 {
print("Some var is less than 100")
}
Swift doesn’t support following representation
if someVar < 100
print("Some var is less than 100")
Typeinference
Swift introduces type safety to iOS development. Once a variable is declared with a particular type, its type is static and
cannot be changed. The compiler is also smart enough to figure out (or infer) what type your variables should be based on
the values you assign them:
var someInt = 100
// OR
var someInt:Int
someInt = 150
someInt = “someInt” // error: Cannot assign value of type String to type Int
Tuples
Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to
be of the same type as each other.
var var1:(Int, String, Double) = (12, "John", 32.6)
print(var1.0, var1.1, var1.2)
Tuples are extremely convenient as return types for functions that need to return more than one value:
func intDivision(a: Int, b: Int) -> (quotient: Int, remainder: Int) {
return (a/b, a%b)
}
print(intDivision(11, 3)) // (3, 2)
let result = intDivision(15, 4)
print(result.remainder) // 3
STringInterpolation
In Swift string formatting is done using string interpolation
let width = 2
let height = 3
let s = "Area for square with sides (width) and (height) is (width*height)"
Functionalprogrammingpatterns
Swift incorporates a number of functional programming features, such as map and filter, which can be used on any
collection which implements the CollectionType protocol.
let arary = [4, 8, 16]
print(array.map{$0})
// [4, 8, 16]
enumerations
Enumerations in Swift are much more powerful than in Objective-C. As Swift structs, they can have methods, and are passed
by value:
enum Location {
case Address(city:String, street:String)
case Coordinates(lat:Float, lon:Float)
func printOut() {
switch self {
case let .Address(city, street):
print("Address: " + street + ", " + city)
case let .Coordinates(lat, lon):
print("Coordiantes: ((lat), (lon))")
}
}
}
let loc1 = Location.Address(city: "Boston", street: "33 Court St")
let loc2 = Location.Coordinates(lat: 42.3586, lon: -71.0590)
loc1.printOut() // Address: 33 Court St, Boston
loc2.printOut() // Coordiantes: (42.3586, -71.059)
functions
In Swift functions are first class types.This means that you can assign functions to variables, pass them as parameters to
other functions, or make them return types.
To read more on function go to
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.htm
l#//apple_ref/doc/uid/TP40014097-CH10-XID_243
references
● https://developer.apple.com/swift/
● https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
● https://en.wikipedia.org/wiki/Swift_(programming_language)
● https://swift.org/documentation/#api-design-guidelines
● https://medium.com/@mergesort/the-expressive-nature-of-swift-b699369dfe95#.42mde6p50
● http://www.infoworld.com/article/2920333/mobile-development/swift-vs-objective-c-10-reasons-the-future-favors-swift.html
● https://www.quora.com/What-are-the-major-differences-between-Swift-and-Objective-C
● https://redwerk.com/blog/10-differences-objective-c-swift
● https://www.toptal.com/swift/from-objective-c-to-swift

Start with swift

  • 1.
  • 2.
    Whatisswift???? Swift was introducedat Apple's 2014 Worldwide Developers Conference (WWDC). Swift is a powerful language that is easy to learn. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works. It provides seamless access to existing Cocoa frameworks and mix-and-match interoperability with Objective-C code It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app.
  • 3.
    Swiftfeatures 1.Safe:Swift eliminates entireclasses of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, and memory is managed automatically. Another safety feature is that by default Swift objects can never be nil. 2.Fast:Swift was built to be fast. Using the incredibly high-performance LLVM compiler, Swift code is transformed into optimized native code that gets the most out of modern hardware. 3.Expressive: Expressive means that it’s easy to write code that’s easy to understand, both for the compiler and for a human reader.
  • 4.
    SimilaritiestoC Most C operatorsare used in Swift, but there are some new operators. Curly braces are used to group statements. Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new identity operator, ===, is provided to check if two data elements refer to the same object. Control statements while, if, and switch are similar, but have extended functions, e.g., a switch that takes non-integer cases, while and if supporting pattern matching and conditionally unwrapping optionals, etc.
  • 5.
    swiftvs.objectiveC ● Swift supportssafe memory management, strong typing, generics and optionals, simple but strict inheritance rules. ● Swift is cleaner and more readable than Objective-C. There are modules that eliminate class prefixes. It also has half as many files in a project, and understandable closure syntax. ● Swift allows to create flexible and lightweight classes which contain exactly what you want. ● Swift is faster than Objective-C. ● Swift supports a limited operator overloading. Objective-C does not. ● Many things like structs, enums, and scalar types are first-class objects in Swift that are not objects in Objective-C ● Swift supports Tuples. Objective-C does not.
  • 6.
    Swiftprogrammingfeatures ● Variables &Constants ● Optionals ● Control Flow ● Type Inference ● Tuples ● String Interpolation ● Functional Programming Patterns ● Enumerations ● Functions
  • 7.
    Variables&constants In Swift weuse var and let keyword to declare a variables/constants. var someVar = 100 // variable whose value can be updated Var someStr = “Some String” let const1 = 120 // constant whose value can not be changed Let constSTr = “Constant String”
  • 8.
    optionals Optionals are nota part of Objective C. They allow functions which may not always be able to return a meaningful value (i.e. a valid o/p) to return either a value encapsulated in an optional or nil. In C and Objective-C, we can already return nil from a function that would normally return an object, but we don’t have this option for functions which are expected to return a basic type such as int, float, or double. This is performed with the ! operator: let result = anOptionalInstance!.someMethod() In this case, the ! operator unwraps anOptionalInstance to expose the instance inside, allowing the method call to be made on it. If anOptionalInstance is nil, a null-pointer error occurs. let myValue = anOptionalInstance?.someMethod() In this case the runtime only calls someMethod if anOptionalInstance is not nil, suppressing the error.
  • 9.
    Controlflow Anyone who’s programmedin C or a C-like language is familiar with the use of curly braces ({}) to delimit code blocks. In Swift, however, they’re not just a good idea: they’re the law! if someVar < 100 { print("Some var is less than 100") } Swift doesn’t support following representation if someVar < 100 print("Some var is less than 100")
  • 10.
    Typeinference Swift introduces typesafety to iOS development. Once a variable is declared with a particular type, its type is static and cannot be changed. The compiler is also smart enough to figure out (or infer) what type your variables should be based on the values you assign them: var someInt = 100 // OR var someInt:Int someInt = 150 someInt = “someInt” // error: Cannot assign value of type String to type Int
  • 11.
    Tuples Tuples group multiplevalues into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other. var var1:(Int, String, Double) = (12, "John", 32.6) print(var1.0, var1.1, var1.2) Tuples are extremely convenient as return types for functions that need to return more than one value: func intDivision(a: Int, b: Int) -> (quotient: Int, remainder: Int) { return (a/b, a%b) } print(intDivision(11, 3)) // (3, 2) let result = intDivision(15, 4) print(result.remainder) // 3
  • 12.
    STringInterpolation In Swift stringformatting is done using string interpolation let width = 2 let height = 3 let s = "Area for square with sides (width) and (height) is (width*height)"
  • 13.
    Functionalprogrammingpatterns Swift incorporates anumber of functional programming features, such as map and filter, which can be used on any collection which implements the CollectionType protocol. let arary = [4, 8, 16] print(array.map{$0}) // [4, 8, 16]
  • 14.
    enumerations Enumerations in Swiftare much more powerful than in Objective-C. As Swift structs, they can have methods, and are passed by value: enum Location { case Address(city:String, street:String) case Coordinates(lat:Float, lon:Float) func printOut() { switch self { case let .Address(city, street): print("Address: " + street + ", " + city) case let .Coordinates(lat, lon): print("Coordiantes: ((lat), (lon))") } } } let loc1 = Location.Address(city: "Boston", street: "33 Court St") let loc2 = Location.Coordinates(lat: 42.3586, lon: -71.0590) loc1.printOut() // Address: 33 Court St, Boston loc2.printOut() // Coordiantes: (42.3586, -71.059)
  • 15.
    functions In Swift functionsare first class types.This means that you can assign functions to variables, pass them as parameters to other functions, or make them return types. To read more on function go to https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.htm l#//apple_ref/doc/uid/TP40014097-CH10-XID_243
  • 16.
    references ● https://developer.apple.com/swift/ ● https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ ●https://en.wikipedia.org/wiki/Swift_(programming_language) ● https://swift.org/documentation/#api-design-guidelines ● https://medium.com/@mergesort/the-expressive-nature-of-swift-b699369dfe95#.42mde6p50 ● http://www.infoworld.com/article/2920333/mobile-development/swift-vs-objective-c-10-reasons-the-future-favors-swift.html ● https://www.quora.com/What-are-the-major-differences-between-Swift-and-Objective-C ● https://redwerk.com/blog/10-differences-objective-c-swift ● https://www.toptal.com/swift/from-objective-c-to-swift