• Home
  • Quick Bytes
  • Algorithms
  • Java
  • iOS
  • Android
  • Certifications
  • About Me

Lets Code Them Up!

  • Learning Swift : Optionals

    November 7th, 2016

     

    Hello Friends,

    Megha here, 

    Have you guys read “Dark Places” by Gillian Flynn? I recently finished it. It is a pretty awesome murder mystery. It is a story of a girl who loses her family at a very young age in a horrible episode. When she grows up, she ventures on a journey to find out what exactly transpired that day. Do give it a read. You can find its review here.

    Enough about the book. In this post, we will be learning about ‘Optionals Data Type’.

    This data type is exclusive to swift. You wouldn’t find it in any other programming language such as java or python.

    In our previous post, we deliberated on Type Safety property of Swift. Go ahead and visit it.

    Not just with types, Swift is otherwise also a very safe language.

    In case of java, null values can be assigned to variables and constants. That is not allowed in Swift.

    Why not assign a nil value to a swift variable and see for ourselves?

     

    //variable to store your favourite color
    var favColor : String = nil

     

    optional error 1

     

     

    The compiler immediately throws an error “Nil cannot initialize specified type “String” as we expected.

    Another example:

     

    //constant to store your age
    let age : Int = nil

     

    screen-shot-2016-11-07-at-8-39-31-pm

     

    Similar error for this one too!

    It can also be seen that compiler is suggesting a fix add “?” around type “Int” / “String” to make them optional.

    Swift has given this feature so that you can have a variable or constant which if not initialized can contain a “nil” value.

    What are we waiting for? Let’s remove this error from both our variable and constant by making them optional types.

     

    var favColor : String? = nil
    let age : Int? = nil

     

    optional no error

     

     

    We can clearly see, error vanishes like magic.

    Now we are going to assign a value to our variable:

     

    var favColor : String? = "Red"

     

    It will work without any more impediments.

    Hmm.. But we must check if we can assign an integer value to this string optional. Shouldn’t we?

     

    var favColor : String? = 78

     

    optional error 3

     

    Uh-oh! Compiler has thrown and error “Cannot convert value of type ‘Int’ to specified type ‘String”

    It means we can only assign ‘nil’ or string value to this optional variable.

    So far we discussed two major items :

    1. Optionals are declared using a “?”
    2. They can store either “nil” value or a value of that particular type

     

    Okay, Let’s try and use this optional variable. 

     

    print(favColor)

     

    print optionals

     

    It is being printed. But we can see, it has got itself wrapped inside Optional() keyword.

    We wouldn’t want that while using it somewhere else. Right?      

    So how do we unwrap an optional value?

    We do it by placing “!” after the variable while using it like this:

     

     

    print(favColor!)

     

    optional print 2

     

    We can see now only “Red” is printed.

     

    Optional Binding

     

    It can be used to find out whether an optional variable contains a value or nil.

     

    var favColor : String? = "Red"
    if let color = favColor{
        print(color)
    }else{
        print("No color")
    }

     

    Here we declare an optional favColor and assign a value to it. Then use if let….else to test whether optional has value.

    If let first checks whether the optional has a value. If it has no value, else statement is executed. If it has value then that value is implicitly unwrapped and assigned to the constant color, and following statements are executed. This is called Optional Binding.

     

    optional binding 1

     

    optional binding 2

     

    We will learn more on the if-else and other control flow statements in our next post. Till then practice optionals and leave your questions and thoughts in comments.

     

    PS : You can find the source code of this post here.

     

  • Learning Swift : Types

    October 9th, 2016

     

    Continuing from where we left in Variables and Constants. Let’s talk in detail about the data types in Swift.

    Swift comprises of the following data types :

        1. String

        2. Character

        3. Integer

        4. Double

        5. Floating

        6. Boolean

        7. Optional

     

    The source code of this post is available at Learning Swift – Types

    Lets analyze each of them one by one.

    String

    Strings represents collection of characters, words or sentences. Example :

     

    var firstName : String = "John"
    print(firstName)
    var fullName : String = "John Dang"
    print(fullName)

     

    The output will be John and John Dang respectively

     

    Character

    Character represents single alphabet or number or special symbol. One cannot assign a word or sentence to the character constant or variable. Example :

     

    var alpha : Character = "A"
    print (alpha)
    var beta : Character = "i"
    print (beta)

     

    The output will be “A” and “i” respectively.

     

    Integer

    Integer represents whole numbers. Int in Swift is used to represent signed whole numbers and UInt is used to represent unsigned whole numbers. Example : 

     

    var age : Int = 89
    print (age)
    
    var temp : Int = -78
    print (temp)
    
    var numberOfOranges : UInt = 10
    print(numberOfOranges)
    
    var numberOfApples : UInt = -100
    
    

    Output

    89
    -78
    10

     

    As you can see Int is used for both positive and negative integers 89 and -78. But if you assign -100 to a variable of type UInt, you will get an error like this : “Negative integer ‘-100’ overflows when stored into unsigned type ‘UInt’”

     

    UInt error

     

    Float and Double

    Float and double are used to represent the fractional numbers. Float is used for 32 bit floating numbers while Double is used for 64 bit floating numbers. Example :

     

    var weight : Float = 78.9
    print(weight)
    var height : Double = 9.67786
    print(height)
    

    The output will be 78.9 and 9.67786 respectively

    Boolean

    Boolean represent true/false values. Example :

     

    var light : Bool = true
    print(light)

     

    The output will be true.

     

    We will be analyzing the optional types in our next post. Before rounding up let’s delve into Type Safety and Type Inference features of Swift.

     

    Type Safety

     

    Take a look into the following example to understand this concept :

     

    var dob : Int = 14
    dob = "Hello My date of birth is "

     

    You will receive the error : “Cannot assign value of type ‘String’ to type ‘Int’”

     

    type safety error

     

    Swift makes sure that we never assign value of one type to a variable of another type. As we can see in the above example, when we try to assign value of String type to the variable dob which is of Integer type, an error occurs.

    This is true even when we try to assign value of Integer type to a variable of String type. You get the same error as above.

     

    var id = "A67"
    id = 89

     

    error type safety

    Type Inference

    Take a look at this example :

     

    var score = 14
    print (score)
    

     

    We well receive an output of 14 with no error even when we haven’t defined the type of variable score. This happens because swift automatically derives the type of variable as Integer with the help of its value 14.

     

    If you have any doubts, do post them in the comment section below.

     

  • Learning Swift : Variable and Constants

    October 2nd, 2016

    Hello Everybody….

    All iOS applications are written using Swift Language. So in following post series starting from this one, we would learn more on swift basics.

    In the last post on Installing Xcode, we installed Xcode 8 on our mac.

    Xcode has a playground where we can learn swift language quickly and easily. Before starting on Swift, we need to get acquainted with Playground

    Therefore, we will go through the following topics step by step :

    1. Meet Playground
    2. Comments
    3. Constants
    4. Variable

    Meet Playground

    In this section we will see how to create a playground file and get to look at playground UI minutely.

    Creating a Playground File

    Open Xcode and Click on “Get Started with a playground”

    xcode install complete

    Next enter a filename of your choice and click on “next”

    Enter file name

    Next choose the location where you would like to save the file and click on “create” and “finish” on the subsequent screen.

    select location

    Your playground file is created and would open like this with some default text.

    playground

    What’s what in Playground?

    play-windows

    1. Navigation Window : This window opens when you click on the first button in the panel shown by arrow. This shows all the files in your playground.
    2. Source Code : Here we write in our swift code.
    3. Result Sidebar : Playground automatically runs and shows the results here. Automatic execution here means, you type in code and you see the results here.
    4. Execution Window : This window opens when we click on the second button in the panel shown by arrow. It has a run button (blue triangle). When clicked, displays the result of swift code. It is used for manual execution.
    5. File and Library Inspector : This window opens when we click on the third button in the panel shown by arrow. File inspector shows the details about the file and library inspector is used to add components from code library to the source code.

    You can find the source code for this post at Learning Swift – Variables and Constants

    Comments 

    Comments are the lines of code which are ignored at the time of execution of code. In swift single line comments are written using “//” and multi-line comments are written within “/* ….. */”

    For Example :

    //Variable and Constants. This is a single line comment
    /* This is a multi-line comment. You can have more than one line. */

    Constants

    Constants are those values which cannot change during execution.

    For Example :

    let firstName : String = "John"
    

    Here firstName is the name of the constant.

    String is the type of firstName and

    “John” is the value assigned to firstName.

    This whole line is called an expression

    Let’s try to change the value of firstName

    firstName = "Dave"

    Playground throws an error like this :

    error

    Variables

    Variables are those values which can be changed during execution. There will be no error shown.

    For example :

    var firstName : String = "John"
    firstName = "Dave"
    print (firstName)

    In line 1, value of firstName is “John”. In second line the value changes to “Dave”. When you will run the above code, the output will be “Dave”.

    In my next post, we will look at various data types in Swift. Till then bbyee.

←Previous Page
1 … 20 21 22

Proudly powered by WordPress

 

Loading Comments...