Anda di halaman 1dari 3

Swi$ 3 Cheatsheet

Variables Classes Control Flow


var meaningOfLife:Int = 42 class Office: Building, Constructable if isActive
let pi:Double = 3.14159265359 // Constant { {
var phi:Float = 1.618 var address:String = "1 Infinite Loop" print("This user is active.")
var message:String = "Welcome" var phone:String? // Optional } else {
var isCurrentUser:Bool = false print("This user is **inactive**")
var three:Int = 1 + 2 // Expression @IBOutlet weak var submit:UIButton? }
var foo = "bar" // Inferred
var optionalMessage:String? // Optional lazy var foo:String = { // Lazy Property var user:String = "Bob"
return "bar";
let a = 3 }() if user == "Alice" && isActive
let b = 60 {
let c = 27 override init() print("Alice is active.")
{ }
var isActive = false address = "1 Probability Drive" else if user == "Bob" && !isActive
} {
print("Bob is lazy.")
func startWorking(_ time:String, }
Func2ons withWorkers workers:Int)
if user == "Deep Thought" || meaningOfLife == 42
func greetUser(name: String, bySaying print("Starting working at time {
greeting:String = "Hello") -> String \(time) with workers \(workers)") print("It's either Deep Thought, or
{ } the meaning of life is 42...")
return "\(greeting), \(name)" } }
}

let message = greetUser(name: "Reinder",


Instances if c < a && b + c == a
{
bySaying: "Good Morning") var headquarters:Office = Office(); print("This will never happen!")
headquarters.phone = "123-456-789" }
print(message) headquarters.startWorking("09:00",
// Outputs: Good Morning, Reinder withWorkers: 19) for i in 1...5
{
print(i); // 1 2 3 4 5
}

switch a {
case 1:
https://twitter.com/intent/tweet? print("abra")
case 3:
text=Check%20out%20this
Code is art. (Unknown)
print("cadabra")
default:
println(abracadabra")
%20Swift%203%20Cheatsheet }
CLICK TO TWEET
%20for%20making%20iPhone while b <= 60 && b > 0
{
print(b)
b -= 1
}

Strings Op2onals Dic2onaries


var me:String = "App Maker" var bill = "133.70" var futurama:[String: String] = [
var ceo:String = "CEO" var optionalNumber:Double? = Double(bill) "Delivery Boy": "Fry",
var title = "\(me), \(ceo)" "Robot": "Bender",
// Optional binding Driver": "Leela",
var amount:String = "1234" if let definiteNumber = optionalNumber "Why Not": "Zoidberg?",
var num:Int? = Int(amount) // Optional { "Idiot": "Zapp Brannigan"
print(definiteNumber) ]
}
for (job, name) in futurama
// Force-unwrapping {
if(optionalNumber != nil) print("\(name), \(job)");

Share The Love {


print(optionalNumber!)
}

https://twitter.com/ } var fry = futurama["Delivery Boy"]

Check out this neat


intent/tweet?
text=Check%20out
Swi6 Cheatsheet for Special / Intermediate Arrays
%20this%20Swift // Optional chaining var hitchhikers:[String] = ["Ford",

making iPhone apps: cell?.label?.text = "Hello World!" "Arthur", "Zaphod", "Trillian", "Marvin",
"Slartibartfast"]
%203%20Cheatsheet // Nil-coalescing operator: default value if nil
h=p://bit.ly/2diz7Um
%20for%20making
var meaningOfLife:Int = deepThought.think() ?? 42; hitchhikers += ["Deep Thought"]

// Downcasting with optional binding var humma:String = "Humma Kavula"

via @reinderdevries
%20iPhone if let book = item as? Book
{
hitchhikers += [humma]

var zaphod:String = hitchhikers[2] // Not 3


%20apps:&url=http://
CLICK TO TWEET
}
for character:String in hitchhikers {
// Force downcasting print(character)
var book = item as! Book }
Closures Guard & Defer Tuples
var closure = { func isMersenne(_ a: Int) -> Bool let coffee = ("Frappuccino", 5.99)
(name:String, clearance:Int) -> Bool in {
guard a > 0 else { let (coffeeType, coffeePrice) = coffee
return name == "Reinder" return false print(coffeeType) // Frappuccino
&& clearance > 7 }
} let (_, justThePrice) = coffee
// Do the magic print(justThePrice) // 5.99
let auth = closure("Reinder", 9)
return true let flight = (code: "XJ601", heading:
func doTask(completionHandler: () -> Void) } "North", passengers: 216)
{ print(flight.heading) // North
// Do the task, then call completionHandler let prime = isMersenne(127)
}
func createLog()
doTask(completionHandler: { { Error Handling
// Do this when task finishes let file = fopen()
}) enum MonkeyError: Error {
defer { case angry
doTask { fclose(file) case tired
// Identical as above! } case sad
} }
let statusA = getInputStatus()
func monkeyMadness() throws
guard statusA != "error" else
Generics {
{
throw MonkeyError.angry
return }
func generateClones<T>(of clone: T, howMany }
n: Int) -> [T] do {
{ file.write(statusA) try monkeyMadness()
var cloneContainer : [T] = [] }
let statusB = getOutputStatus() catch let error {
for _ in 0 ..< n print(error)
{ guard statusB != "interrupted" else }
cloneContainer.append(clone) {
} return
}
return cloneContainer
} file.write(statusB)
}
let clones = generateClones(of: "Agent
Smith", howMany: 100) Further reading: https://developer.apple.com/library/ios/documentation/Swift/
Conceptual/Swift_Programming_Language/TheBasics.html

LearnAppMaking.com 2016
v. 1.1 for Swift 3.0

Anda mungkin juga menyukai