Python Vs Swift

Simple Data Types

You can’t mix floats and integers in Swift for calculations

SwiftPython
let apples = 3let appleSummary = “I have \(apples) apples.”

apples = 3appleSummary =”I have” + str(apples) + “apples”// orappleSummary = “I have {} apples”.format(apples)

Combining variables and text

SwiftPython
print(“This is \(name) He has \(apples) apples.”)

print(“This is”,name,”he has”,apples,”apples”)// or print(“This is {} he has {} apples”.format(name, apples))

Arrays

Swift Arrays are similar to Python Lists and they can both grow! 

(Not like what our exam board believes!) 

Use let to create unmutable arrays and dictionaries (can’t change)

Use var to create mutable arrays and dictionaries (can change)

Warning ARRAYS Must be the same Data type in Swift! 

Dictionaries keys and values must be consistent data type in Swift (although keys’ type can be different type from values’ type)

Selection

Return of the curlies! 

SwiftPython
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores
{    if score > 50
{        teamScore += 3    }
else {        teamScore += 1    }}
print(teamScore)
individualScores = [75, 43, 103, 87, 12]
teamScore = 0
for score in individualScores:    
if score > 50:         
teamScore += 3    
else:        
teamScore += 1print(teamScore)

Optionals

In Python we indicate None to mean that the variable is “blank” or has no legit value. Any variable can be assigned None, and we check for None with:

if variable is None:

// or

if variable == None:  // first way is better!

In Swift we can’t just give a variable nil value, unless we have already declared it as an Optional. This is because Swift has a “stronger” type system, but Python type system is “weaker”.

SwiftPython
var spouceName: String? = nil  // singlespourceName = “Lucy”  // married to Lucy
If (spouceName == nil) {  print(“Not married”)} else {  print(“Married to \(spouceName)”)}
spouceName = None  # singlespouceName = “Lucy”  # married
if (spouceName is None):  print(“Not married”)else:  print(“Married to {}”.format(spouceName))

Switch

Just like “case of” in Pseuodocode! 

SwiftPython iGCSE
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.”)}
if vegetable == “celery”:    print(“Add some raisins and make ants on a log.”)elif vegetable in [“cucumber”, “watercress”]:    print(“That would make a good tea sandwich.”)elif “pepper” in vegetable:    print(“Is it a spicy”,vegetable,”?”)else:    print(“Everything tastes good in soup.”)


A-levelvegetable = “celery”{“celery”: “Add some raisons”, “cucumber”: “That would make a good tea sandwhich”, “watercress”: “That would make a good tea sandwhich”}.get(vegetable)

While and Repeat

SwiftPython
var n = 2while n < 100 {    n *= 2}print(n)n = 2while n < 100:    n *= 2print(n)
var m = 2repeat {    m *= 2} while m < 100print(m)m = 2while True:    m *= 2    if m > 100: break #changed operatorprint(m)

Functions (AS level)

Python functions don’t need to have the types declared, but Swift does. In Swift, each parameter has to have its type declared, as well as its return type. Python 3 introduced a way to include type information; but it is just a comment and is not enforced.

SwiftPython
func greet(person: String, day: String) -> String {}def greet(person,day):    pass

#python3 alternativedef greet(person: str, day: str) -> str:

Classes (A2)

Quite close, but need to look at individual docs. 

SwiftPython
class Square: NamedShape {    var sideLength: Double
    init(sideLength: Double, name: String) {        self.sideLength = sideLength        super.init(name: name)        numberOfSides = 4    }
    func area() -> Double {        return sideLength * sideLength    }
    override func simpleDescription() -> String {        return “A square with sides of length \(sideLength).”    }}let test = Square(sideLength: 5.2, name: “my test square”)test.area()test.simpleDescription()
class square:    def __init__(self, sideLength, name):        self.sideLength = sideLength        name = name        numberOfSides = 4    def area(self):        return self.sideLength * self.sideLength                def simpleDescription(self):        return “A square with sides of length “+str(self.sideLength)
test = square(5.2,”my test square”)print(test.area())print(test.simpleDescription())

See http://openbookproject.net/thinkcs/python/english3e/classes_and_objects_I.html for Python Classes.