Saturday, February 11, 2017

Optional(?) - Swift3 Coding Tutorial

Open Xcode.Click on Get Started with Playground.Name the playground.Then Create.


Then type following codes or copy it.

//Optional can have value or nil representing that value is missing.Question mark after the value to mark it as optional

var schoolName : String

var studentName : String? = nil

//As schoolName is not optional need to be initialized before its use

//print(schoolName)

//In optional the value might be missing

if(studentName != nil )
{
    print(studentName! ) //because this value can not be nil.so no harm to force unwrap
}
else
{
    print(studentName ?? "some value")//Give default value incase nil

}

No comments:

Post a Comment