Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Compile and Execute Swift Online

// Your code here!
import Foundation
import Glibc

// This is a comment. It is not executed.
/* This is also a comment.
 Over many...
 many...
 many lines. */
print("Hello, Swift Apprentice reader")
 
// constants - Implicit
print( "-----------------constants - Implicit-----------------")
let integerNo = 1;
let floatNo = 0.1;
let doubleNo = 3.14;
let stingVal = "My String Value"
print("constants are declared by implicitly:: \n integerNo:: \(integerNo)");


let myConstant = 42
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
let label = "The width is "

let width = 94
let widthLabel = label + String(width)
print("width :: \(widthLabel) ")
let apples = 3.0
let oranges = 5.0
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

print("Summary:: \n  apple summary :: \(appleSummary)  \n  fruits summary::: \(fruitSummary)  ")

let quotation = """
-------------------------------------------
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
------------------------------------------------
"""

print("quotation:: \n  \(quotation) ")

let myArray = ["catfish", "water", "tulips"]  // immutable
let myDictionary = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]  // immutable

let myArray1stobj = myArray[0]
let myDictKeyValue = myDictionary["Kaylee"]
print("my array ::  \(myArray) and my firstobj \(myArray1stobj)")
print("myDictionary ::  \(myDictionary) and 'kaylee' key value  is \(myDictKeyValue)")


// constants - Expilict

print( "-----------------constants - Expilict-----------------")


let explictInt : Int = 1;
let explictFloat : Float = 0.1;
let explictDouble : Double = 3.14;
let explictStr : String = "My String Value"
print("constants are declared by explicitly:: \n integerNo:: \(explictInt)");

print("sum of the above constants:: \n  \(Double(explictInt) + Double(explictFloat) + explictDouble) ");


// Variables - Implicit

print( "-----------------Variable - Implicit-----------------")

var implicitIntVar = 1
var implicitfloatVar  = 0.1
var implicitDoubleVar  = 3.14
var implStringVar  = "My implicit Varibale"

print("Variables are declared by implicit:: \n implicitIntVar:: \(implicitIntVar)");
var shoppingList = ["catfish", "water", "tulips"]
shoppingList[1] = "bottle of water"
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
print("shoppingList==: \(shoppingList)  \n occupations==: \(occupations)")

// Variables - Implicit

print( "-----------------Variable - Explicit-----------------")

var explicitIntVar : Int = 1
var explicitfloatVar : Float  = 0.1
var explicitDoubleVar : Double  = 3.14
var explStringVar : String = "My explixt Varibale"

print("Variables are declared by explixt:: \n explicitIntVar:: \(explicitIntVar)");




// Empty array & dictionary

print( "-----------------Empty array & dictionary-----------------")


let emptyArray = [Int]() 
let emptyDictionary = [String: Float]()
print("constants for emptyArray==: \(emptyArray)  \n emptyDictionary==: \(emptyDictionary)")

var emptyArrayVar =  [Int]() 
var emptyDictionaryVar = [String: Float]()
     emptyArrayVar.append (1)
     emptyArrayVar[0] = 2
  
    
    emptyDictionaryVar["key1"] = 1.0
    emptyDictionaryVar["key2"] = 2.0
print("variable for emptyArrayVar==: \(emptyArrayVar)  \n emptyDictionaryVar==: \(emptyDictionaryVar)")

// optional , wrapping and unwrapping
print( "-----------------optional , wrapping and unwrapping-----------------")

let optionalIntConSt : Int? = 1;
print("optionalInt \(optionalIntConSt)" )

var optionInt : Int?
print("optionalInt \(optionInt)" )
optionInt = 3
print("optionalInt \(optionInt!)" )  // use ! to unwrap the contained value of optional

 
let intString = "9"
let doubleString : String = "3.14"
var myString = "a"
let someInteger = Double(doubleString)
// someInteger contains a value
if someInteger != nil {
 print("someInteger contains a value. Here it is: \(someInteger!)")
}
else {
 print("someInteger doesn't contain an integer value.")
}


var intStingVar = "1"
let tempIntStingVar = Int(intStingVar)
if tempIntStingVar != nil {
 print("tempIntStingVar contains a value. Here it is: \(tempIntStingVar)")
}
else {
 print("tempIntStingVar doesn't contain an integer value.")
}

if let x = tempIntStingVar {
     print("tempIntStingVar contains a value. Here it is: \(tempIntStingVar)")
         print("x contains a value. Here it is: \(x)")

}else{
     print("tempIntStingVar contains a value. Here it is: \(tempIntStingVar)")

}
//Implicitly Unwrapped Optionals
var optionalString: String? = "My optional string."
var forcedUnWrappedString: String = optionalString! // requires an !
var nextOptionalString: String! = "An implicitly unwrapped optional."
var implicitUnwrappedString: String = nextOptionalString // no need for an !

// Loop or looping statements
// /Loop Type
print( "-----------------Loop Type -----------------")
 print( "Loop Type :::  For In ::")
var someInts:[Int] = [10, 20, 30]
let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

// Find the largest numbers
var largest = 0
for (kind, numbers) in interestingNumbers {
    print("numbers:: \(numbers)")
    print("kind:: \(kind)")
    for number in numbers {
         print("number:: \(number)")
        if number > largest {
            largest = number
        }
    }
}

  

for index in someInts {                   // For - In
   print( "Value of index is \(index)")
}

print( "Loop Type :::  while ::")
var index = 10    
while index < 20 {                      // while
   print( "Value of index is \(index)")
   index = index + 1
}

print( "Loop Type :::  repeat while ::")
index = 10       // Repeat while
repeat {
   print( "Value of index is \(index)")
   index = index + 1  
}
while index < 20


// Loop Control Statements
print( "-----------------Loop Control Statements-----------------")
print( "Loop control :::  continiue ::")
index = 10                              // continiue
repeat {
   index = index + 1
   if( index == 15 ){
      continue                             
   }
   print( "Value of index is \(index)")
} while index < 20

print( "Loop control :::  break ::")
index = 10                              // continiue
repeat {
   index = index + 1
   if( index == 15 ){
      break
   }
   print( "Value of index is \(index)")
} while index < 20


// Using Loops to Repeat Program Statements
// A Count-Controlled Loop
print( "-----------------Using Loops to Repeat Program Statements-----------------")
print( "-----------------A Count-Controlled Loop-----------------")
for i in 0..<10 {
    print("The index is: \(i)")
}
//A Count-Controller Loop Using the Closed-Range Operator
print( "-----------------A Count-Controller Loop Using the Closed-Range Operator-----------------")
for i in 0...10 {
    print("The index is: \(i)")
}

var total = 0
for i in 0..<4 {
    total += i
}
print("for in type  0..<4 :: \(total)")

total = 0
for j in 2..<4 {
    total += j
}
print("for in type  2..<4 :: \(total)")


total = 0
for k in stride(from:4, to: 0, by:-1) {
    total += k
}
print("for in stride(from:4, to: 0, by:-1) :: \(total)")

total = 0
for k in stride(from: 4, through: 0, by: -1){
    total += k
}
print("for in stride(from: 4, through: 0, by: -1) :: \(total)")



// Condition-Controlled Loops
print( "-----------------Condition-Controlled Loops-----------------")
var isTrue = true
while isTrue {
// do something
  isTrue = false // a condition occurs that sometimes sets isTrue to FALSE
  print( "a condition occurs that sometimes sets isTrue to FALSE :: \(isTrue)")
}

// control flow

// Control Flow
print( "-----------------Decision Making Control Flow Statements-----------------")
// if - else if - else
print( "if - else if - else statement::-->")

let individualScores = [75, 43, 100, 87, 12]
var teamScore = 0
for score in individualScores {
    if score == 100{
       teamScore += 10
    }else if score > 50 {
       teamScore += 3
    } else {
      teamScore += 1
    }
}
print( "teamScore in if - else if - else statement \(teamScore)")

// if - else 
print( "if - else statement::-->")
var optionalName: String? = "greeting"
var greeting = "Hello!"

if let name = optionalName {
    greeting = "Hello, \(name)"
}else{
    greeting = "Hello, nil"
}
print( "greeting if - else statement \(greeting) ")

var optionalStrName: String?
if optionalStrName == nil {
    greeting = "Hello, nil"
}else{
    greeting = "Hello, \(optionalStrName)"
}
print( "greeting if - else statement \(greeting) ")



var nickName: String? = "Jnick"
var fullName: String? = "John Appleseed"
var informalGreeting = "Hi \(nickName) \(fullName)"
informalGreeting = "Hi "+nickName! + fullName!
informalGreeting = "Hi \(nickName ?? fullName)"

// switch case statement
print( "switch case statement::-->")

let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

var switchStr = "red pepper6"
switch switchStr {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasPrefix("red") || x.hasSuffix("pepper") :
    print("Is it a red coloured spicy pepper\(x)?")
case "10":
    print("It is a actual value")
default:
    print("Everything tastes good in soup.")
}

// Advanced variable Tubles,Array,Dictionary

// Tuples
print( "Tuples::-->")

var error501 = (errorCode: 501, description: "Not Implemented")
print(error501.errorCode)   // prints 501.
print(error501.1)   // prints 501.

//func to get min ,max and sum of given array of values
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    
    return (min, max, sum)
}
var statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])

print("Tuples example \n Sum: \(statistics.sum) \n max: \(statistics.max) \n min: \(statistics.min)  \n  1st arg: \(statistics.1)")


// Arrays
print( "Arrays::-->")
// A mutable array of Strings, initially empty.

var someIntts = [Int]() // invoking the [String] initializer
//var someStrs = [String]=[]  // type annotation + array literal
//var somedouble = Array<Double>()// without syntactic sugar

// adding element
someIntts.append(20)
someIntts.append(30)
someIntts += [40]

// accessing element
var someVar = someIntts[0]
// modifying element
someIntts[2] = 50


// count property
print("count of someIntts \(someIntts.count)")
// Empty property
print("is someIntts  empty array   \(someIntts.isEmpty)")
/*
// adding two arrays with same type
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)

var intsC = intsA + intsB
for item in intsC {
   print(item)
}
*/

// ------------------------Sets--------------------------------
print( "Sets::-->")


var evens: Set = [10,12,14,16,18,2]
var odds: Set = [5,7,9,11,13]
var primes = [2,3,5,7]

// count property
print("evens set count \(evens.count)")
// isEmpty property
print("isEmpty evens set  \(evens.isEmpty)")

// insert property
evens.insert(20)
evens.insert(22)
// contains property
print(" evens set  contains 22\(evens.contains(22))")

// remove property
evens.remove(22)
print(" evens set  \(evens)")


// union
print(" odds set after union operation  \(odds.union(evens).sorted())")  // [5,7,9,10,11,12,13,14,16,18]
// intersection
print(" odds set after intersection operation  \(odds.intersection(evens).sorted() )") //[]
// subtracting
print(" odds set after subtracting operation  \(odds.subtracting(primes).sorted() )") //[9, 11, 13]
// iterate set
for items in evens.sorted() {
   print(items)
}

// ------------------Dictionaries---------------------
print( "Dictionaries::-->")
// Empty dictinary
var books = [Int: String]()
// or 
var books2: [Int: String] = [:]
var books3: [Int: String] = [1: "Book 1", 2: "Book 2"]
var otherBooks = [3: "Book 3", 4: "Book 4"]

print("dictinary object :: \n Books: \(books) \n Books2: \(books2) \n \(books3) \n otherBooks:  \(otherBooks) ")

// Accessing elements and iterating values
books  = [1: "Book 1", 2: "Book 2"]
let bookName = books[1]

for book in books.values {   // through using the values property:
print("Book Title: \(book)")
}

for bookNumbers in books.keys { // through using the keys property:
print("Book number:: \(bookNumbers)")
}

for (book,bookNumbers)in books{   // To get all key and value pair corresponding to each other
print("\(book) \(bookNumbers)")
}

// Modifying Dictionaries
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("New value of one", forKey: 1)
var someDictVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)" )
print( "Value of key = 1 is \(someDictVar)" )
print( "Value of key = 2 is \(someDict[2])" )
someDict[1] = "old value is inserted"
someDict[4] = "four"
var newkeyval = someDict.updateValue("New value of one to add 5", forKey: 5)
print("newkeyval dict:: \(newkeyval)")
someDictVar = someDict[1]
print( "Value of key = 1 is \(someDictVar!)" )
print("modified dict:: \(someDict)")

// -------------------Enumerations ---------------------------
print( "Enumerations::-->") 
// enum with switch case
enum Climate {
   case India
   case America
   case Africa
   case Australia
}

var season = Climate.America
season = .America
switch season {
   case .India:
      print("Climate is Hot")
   case .America:
      print("Climate is Cold")
   case .Africa:
      print("Climate is Moderate")
   case .Australia:
      print("Climate is Rainy")
   
}

enum Month: Int {
   case January = 1, February, March, April, May, June, July, August,
      September, October, November, December
}

let yearMonth = Month.May.rawValue
print("Value of the \(Month.May) Month is: \(yearMonth).")

// Nested Enumerations
print( "Nested Enumerations::-->") 

enum Orchestra {
        enum Strings {
                case violin
                case viola
                case cello
                case doubleBasse
        }
        enum Keyboards {
            case piano
            case celesta
            case harp
        }
        enum Woodwinds {
            case flute
            case oboe
            case clarinet
            case bassoon
            case contrabassoon
        }
    }

let instrment1 = Orchestra.Strings.viola
let instrment2 = Orchestra.Keyboards.piano
print( "instrment1:: \(instrment1) instrment2:: \(instrment2)") 


// structs
print( "-----------------------structures::-------------------------") 

struct Repository {
    let identifier: Int
    let name: String
    var description: String?
}

let newRepository = Repository(identifier: 0, name: "New Repository", description: "Brand NewRepository")
print("newRepository:: \(newRepository)")
print("newRepository name:: \(newRepository.name)")

// mutating structures
print( " mutating structures::-->") 

struct Counter {
    private var value = 0
    
    mutating func next() {
        value += 1
    }
}
var counter = Counter()
counter.next()
counter.next()
print("counter values:: \(counter)")
var counter1 = Counter()
counter1.next()
print("counter1 values:: \(counter1)")


// -------------------------------Functions::-------------------
print(" --------------------------------Functions::-------------------")
// Basic Use
func basicFunction()
{
    print("basicFunction:::")
}
//Functions with Parameters
func funcWithParam(someInteger: Int , someArray: [Int]){
        print("funcWithParam::: \n given param1 integer::  \(someInteger)");
         print("funcWithParam::: \n given param2 is integer array ::  \(someArray)");

}
funcWithParam(someInteger:12 ,someArray:[12,13,14] )


//Functions with Parameters and param names
func funcWithParam(someInteger: Int ,withArray someArray: [Int]){
        print("funcWithParam AndParam Name label::: \n given param1 integer::  \(someInteger)");
         print("funcWithParam AndParam Name label::: \n given param2 is integer array ::  \(someArray)");

}

funcWithParam(someInteger: 12, withArray:[15,17,19])


//function with parameter and returntype
func greet1(person: String, day: String) -> String {
    return " return type func:: \n Hello \(person), today is \(day)."
}
print (" \(greet1(person: "Bob", day: "Tuesday"))")


// A function can take another function as one of its arguments.
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 9, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)

//---------------------------------Closures-----------------------
let studname = { print("Welcome to Swift Closures::------>") }
studname()

let divide = {
   (val1: Int, val2: Int) -> Int in 
   return val1 / val2 
}

let result = divide(200, 20)
print (result)

var count:[Int] = [5, 10, -6, 75, 20]
let descending = count.sorted(by: { n1, n2 in n1 > n2 })
let ascending = count.sorted(by: { n1, n2 in n1 < n2 })

print(descending)
print(ascending)

let numb = [98, -20, -30, 42, 18, 35]

let asc = numb.sorted(<)
print(asc)

// --------------------------------Error Handling::-------------------
print(" --------------------------------Error Handling::-------------------")

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.