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

Session2

import Foundation
import Glibc

/*
var a: Int = 5
var b: Int = 7 
var b1 = true

print("The sum is \(a+b) , the Subtract is \(a-b) , the Multiply is \(a*b) , the Dividing is \(a/b) , and the rest of the division is \(a%b)")
print("Are A and B is equal? \(a==b)")
print((a>b) && (a != b))
print(!b1)

//----------------------------------------------------------------------------------------------
//EX1 Solution :
var a: Int = 5
var b: Int = 7
var sum: Int = a + b
print(sum)
//----------------------------------------------------------------------------------------------

//EX2 Solution :

let secondsInAMinute = 60

// The number of seconds in a hour is 60 times the number 
// of seconds in a minute, which is 60.
let secondsInAHour = 60 * secondsInAMinute

// The number of seconds in a day is 24x the number of seconds in a hour. 
let secondsInADay = 24 * secondsInAHour

// The number of seconds in a year is 365x the number of seconds in a day. 
let secondsInAYear = 365 * secondsInADay

print(secondsInAYear)
//----------------------------------------------------------------------------------------------


//Ex3 Solution :
var widthOfScreen: Int = 30
var heightOfScreen: Int = 20

let numberOfPixels = widthOfScreen * heightOfScreen
print(numberOfPixels)

//----------------------------------------------------------------------------------------------

*/
let a: Int
let b: Int
let sumOfValues: Int = 10
let diffOfValues: Int = 4
b = (sumOfValues - diffOfValues) / 2
a = sumOfValues - b

print("a = \(a) and b = \(b)")

//OR

let value1: Int
let value2: Int
let sumOfValues2: Int = 10
let diffOfValues2: Int = 4
value1 = (sumOfValues + diffOfValues) / 2
value2 = sumOfValues - value1

print("Expected value of value1 = \(value1)  &  Expected value of value2 = \(value2)")













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::-------------------")

Compile and Execute Swift Online

var IsLogin = false
if IsLogin == true
{ print ("yes")}
else {print ("no")}

var x = 10 
if x >= 90 
{print ("A")}
else if x >= 80
{print ("B")}
else if x >= 70 
{print ("C")}
else if x >= 60 
{print ("D")}
else if x >= 50 
{print ("E")}
else
{print ("F")}

var from: Int = 10
var to: Int = 100
var sum: Int = 0

Compile and Execute Swift Online

var p = 125
if p == 10 {
    p = p + 10
    print(p)
} else if p < 10 {
    p = p + 100
    print(p)
} else {
    p = p + 2
    print(p)
    switch p {
        case 127 :
            let stringA = ""
            if stringA.isEmpty{
                print("String is Empty")
                if p == 127 {
                    let char : Character = "Hello"
                    print(" Character value is \(char) ")
                }
            } else {
                print("String is not empty")
            }
        default :
            p = p + 4
            print("P is values \(p) ")
    }
}

Switch Statement Program1

var p = 125
if p == 10 {
    p = p + 10
    print(p)
} else if p < 10 {
    p = p + 100
    print(p)
} else {
    p = p + 2
    print(p)
    switch p {
        case 127 :
            let stringA = ""
            if stringA.isEmpty{
                print("String is Empty")
                if p == 127 {
                    let char : Character = "Hello"
                    print(" Character value is \(char) ")
                }
            } else {
                print("String is not empty")
            }
        default :
            p = p + 4
            print("P is values \(p) ")
    }
}

Basics - variables - datatypes

//import UIKit
//import Cocoa
/*var str = "Hello, playground"
print(str)

/* My first program in Swift 4 */
var myString = "Hello, World!"; print(myString)

// Var Able to change value of it
var Age = 10;
print (Age);
Age = 50;
print (Age);
// Let Not Able to change value of it
let name = "Koky";
print (name);

var num = 10;
print(num)

var dou = 20.3
print(dou)


var nametxt = "Mariam"
var height = 1.5
let greeting = "Hello, "

print (greeting + nametxt)
print (name + " is " + String(height) + "m " + "tall")

// Data Types
var Intval : Int = 20;
var UIntval : UInt = 2022222;
var Floatval :Float = 230.5
var Doubleval : Double = 50.36
var Stringval : String = "eman"
var boolval : Bool = true
var Characterval : Character = "x"



print(UIntval, Intval , Floatval , Doubleval , Stringval , boolval,Characterval)
// Create Own DataType 
typealias Feet = Int
var distances: Feet = 100
print(distances)

var remainder = -13 % 9
print(remainder)
var quotient = 15 / 2
print(quotient)

var distance = 200 //in km
var time = 2.3 //in hours
var speed = Double(distance)/time
print (speed)

print("Items to print \n", separator: "Value \n" , terminator: "Value")
print("\nValue one","Value two", separator: " \nNext Value" , terminator: " \nEnd")

// You can declare variable as Variable Declaration
var intalx = 10;
// You can declare variable as Type Annotations
var intalxx : Int = 10;

var varA = "Godzilla"
var varB = 1000.00

print("Value of \(varA) is more than \(varB) millions")

// Declare Value as optical that not mandatory assign value to parameter
var perhapsInt: Int?
var nnn : Int? = nil


var Inta : Int?
var perhapsStr : String? =  nil
perhapsStr = "Hellow Every Body"

if perhapsStr != nil {print(perhapsStr)} 
else { print("myString has nil value")}

var myString  : String?
myString = "no one else"
if myString != nil{print(myString)}
else{print("myString  Is Nil")}

if test == nil {print("Test Is Nil")}
else {print(test)}
*/
var test : String!
test = "Hello Emy"

if let yourString = test {
   print("Your string has - \(yourString)")
} else {
   print("Your string does not have a value")
}
var error501 = (errorCode: 501, description: "Not Implemented")
print(error501.errorCode)   // prints 501.


let stringL = "Hello\tWorld\n\nHello\'Swift 4\'"
print(stringL)


Compile and Execute Swift Online

import Foundation
import Glibc
 
var error501 = (501, "Not implemented")
var s1:String = "n1"
var s2 = "n2"
let c1:Character = "a"
var arrI = [5,6,3,10,8]
var nul:Bool? = nil
print("The code is \(error501.0)")
print("The definition of error is = \(error501.1)")

print(s1, s2, separator: " - ", terminator: " end ")
s1.append(c1)
print(s1)

print()
print(arrI)
var i = 0
for _ in arrI {
    print(arrI[i])
    i+=1
}
print(nul as Any)
print()

let evens: Set = [10,12,14,16,18]
let odds: Set = [5,7,9,11,13]
let primes = [2,3,5,7]
print(odds.union(evens).sorted())
print(odds.intersection(evens).sorted())
print(odds.subtracting(primes).sorted())
print()
func display(no1: Int) -> Int {
   let a = no1
   return a
}

print(display(no1: 100))
print(display(no1: 200))

func sum(a: Int, b: Int) -> Int {
   return a + b
}
var addition: (Int, Int) -> Int = sum
print(addition(40, 89))

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

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()
print(descending)
print(ascending)

print()
let sub = {
   (no1: Int, no2: Int) -> Int in
   return no1 - no2 
}
let digits = sub(10, 20)
print(digits)

OOP\BK

//Город, район, улица, дом, квартира, жилец

class City {
    var cityName: String
    
    func printProperty()  {
        print("Город: \(cityName)")
    }
    
    init(cityName: String) {
        self.cityName = cityName
    }
}

class Area: City {
    var areaName: String
    
    override func printProperty() {
        super.printProperty()
        print("Район: \(areaName)")
    }
    
    init(cityName: String, areaName: String) {
        self.areaName = areaName
        super.init(cityName: cityName)
    }
}

class Street: Area {
    var streetName: String
    
    override func printProperty() {
        super.printProperty()
        print("Улица: \(streetName)")
    }
    init(cityName: String, areaName: String, streetName: String) {
        self.streetName = streetName
        super.init(cityName: cityName, areaName: areaName)
    }
}

class House: Street {
    var houseNumber: Int
    override func printProperty() {
        super.printProperty()
        print("Номер дома: \(houseNumber)")
    }
    
    init(cityName: String, areaName: String, streetName: String, houseNumber: Int) {
        self.houseNumber = houseNumber
        super.init(cityName: cityName, areaName: areaName, streetName: streetName)
    }
}

class Flat: House {
    var flatNumber: Int
    
    override func printProperty() {
        super.printProperty()
        print("Номер квартиры: \(flatNumber)")
    }
    
    init(cityName: String, areaName: String, streetName: String, houseNumber: Int, flatNumber: Int) {
        self.flatNumber = flatNumber
        super.init(cityName: cityName, areaName: areaName, streetName: streetName, houseNumber: houseNumber)
    }
}

class Person: Flat {
    var name: String
    
    override func printProperty() {
        super.printProperty()
        print("Имя жильца: \(name)")
    }
    
    init(cityName: String, areaName: String, streetName: String, houseNumber: Int, flatNumber: Int, name: String) {
        self.name = name
        super.init(cityName: cityName, areaName: areaName, streetName: streetName, houseNumber: houseNumber, flatNumber: flatNumber)
    }
}

//var city = City(cityName: "Киев")
//city.printProperty()

//var area = Area(cityName: "Киев", areaName: "Святошино")
//area.printProperty()

//var street = Street(cityName: "Киев", areaName: "Святошино", streetName: "Вернадского")
//street.printProperty()

//var house = House(cityName: "Киев", areaName: "Святошино", streetName: "Вернадского", houseNumber: 16)
//house.printProperty()

//var flat = Flat(cityName: "Киев", areaName: "Святошино", streetName: "Вернадского", houseNumber: 16, flatNumber: 1)
//flat.printProperty()

var Jack = Person(cityName: "Киев", areaName: "Святошино", streetName: "Вернадского", houseNumber: 16, flatNumber: 1, name: "Джек")
Jack.printProperty()

pyramid

var str: String = ""
for i in 0..<1 {
    print(i, terminator : " ")
}
print(str)
str = ""
for i in 0..<2 {
    print(i, terminator : " ")
}
print(str)
str = ""

for i in 0..<3 {
    print(i, terminator: " ")
}
print(str)
str = ""

for i in 0..<4 {
    print(i, terminator: " ")
    
}
print(str)
str = ""

for i in 0..<5 {
    print(i, terminator: " ")
}
print(str)
str = ""

for i in 0..<6 {
    print(i, terminator: " ")
}
print(str)
str = ""

print ("")

for i in 0..<6 {
    print(i, terminator: " ")
}
print(str)
str = ""

for i in 0..<5 {
    print(i, terminator: " ")
    }
    print(str)
    str = ""
    
    for i in 0..<4 {
    print(i, terminator: " ")
    }
    print(str)
    str = ""
    
    for i in 0..<3 {
    print(i, terminator: " ")
    }
    print(str)
    str = ""
    
    for i in 0..<2 {
    print(i, terminator: " ")
    }
    print(str)
    str = ""
    
    for i in 0..<1 {
    print(i, " ")
    }
    print(str)
    str = ""

Mutating func in struct

import Foundation
import Glibc
 
protocol Example{
    var desc:String { get }
    mutating func adjust()
    
}
class Ex:Example
{
    var desc="hi this is an example"
    func adjust()
    {
          desc+="Bye now!"
         
    }
}
//var a=Ex();
//a.adjust()
//print(a.desc)

struct Simple:Example
{
    var desc="dks;ks"
    mutating func adjust()
    {
        desc+=("desc")
    }
    
}

var A=Simple()
print(A.desc)
A.adjust()
print(A.desc)

Previous 1 ... 3 4 5 6 7 8 9 ... 61 Next
Advertisements
Loading...

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