Swift playground

Comments

// this is a comment
/* this is also a comment,
but written over multiple lines */
/// This is a function level comment.
///
/// - Parameter onCompletion: Closure to be executed on completion.

Numbers

42
-23
3.14159
0.1
-273.15
1.25e-2
0xC.3p0
1_000_000
1_000_000.000_000_1

Strings

let someString = "Some string literal value 😊"
var emptyString = ""
// String interpolation
let multiplier = 3
"\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"

// Special Characters in String Literals
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024
let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496

let threeDoubleQuotationMarks = """
    Escaping the first quotation mark \"""
    Escaping all three quotation marks \"\"\"
"""

Control flow

for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}
for _ in 1...power {
    answer *= base
}
while square <; finalSquare {
    // roll the dice
    if ++diceRoll == 7 { diceRoll = 1 }
    // move by the rolled amount
    square += diceRoll
    if square <; board.count {
        // if we're still on the board, move up or down for a snake or a ladder
        square += board[square]
    }
}
switch someCharacter {
    case "a", "e", "i", "o", "u":
        println("\(someCharacter) is a vowel")
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
        "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
        println("\(someCharacter) is a consonant")
    default:
        println("\(someCharacter) is not a vowel or a consonant")
}

guard let phone = cleanedPhoneNumber else {
    return nil
}
return URL(string: "telprompt://" + phone)

defer {
    navigationController?.popViewController(animated: true)
}

Classes and attributes

fileprivate class MyViewController: UIViewController {
    @IBOutlet weak var button: UIButton!
    @IBOutlet var textFields: [UITextField]!
    @IBAction func buttonTapped(AnyObject) {
        print("button tapped!")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

open extension MyViewController {}

@IBDesignable
final class MyCustomView: UIView {
    @IBInspectable var textColor: UIColor
    @IBInspectable var iconHeight: CGFloat
    /* ... */

    func resetBadgeCountForAllStores(onCompletion: @escaping (Bool) -> Void)
}

Classes and attributes

@available(iOS 15.0, macOS 10.16, *)
fileprivate class MyViewController: UIViewController {
    @IBOutlet weak var button: UIButton!
    @IBOutlet var textFields: [UITextField]!
    @IBAction func buttonTapped(AnyObject) {
        print("button tapped!")
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

open extension MyViewController {}

@IBDesignable
final class MyCustomView: UIView {
    @IBInspectable var textColor: UIColor
    @IBInspectable var iconHeight: CGFloat
    /* ... */

    func resetBadgeCountForAllStores(onCompletion: @escaping (Bool) -> Void)
}

// Subsequent release renames MyProtocol
protocol MyRenamedProtocol {
    // protocol definition
}

@available(*, unavailable, renamed: "MyRenamedProtocol")
typealias MyProtocol = MyRenamedProtocol

Combine usage

import Combine
protocol PushNotesManager {
    var foregroundNotifications: AnyPublisher<PushNotification, Never> { get }
}

private var subscriptions = Set<AnyCancellable>()
subscriptions.forEach {
    $0.cancel()
}

stores.site.compactMap { $0 }
    .filter { $0.siteID == self.siteID }
    .first()
    .sink { [weak self] site in
        self?.presentStoreSwitchedNotice(site: site)
    }.store(in: &cancellables)

SwiftUI

import SwiftUI

struct ActivityIndicator: UIViewRepresentable {
    typealias ViewModel = ActivityIndicatorViewModel
    @Binding var isAnimating: Bool
    @State var isAnimating: Bool
    @StateObject var viewModel: ViewModel
    @ObservedObject var viewModel: ViewModel
    @EnvironmentObject var viewModel: ViewModel
}

struct ViewModel: ObservableObject {}

@ViewBuilder private func buildNoticeStack() -> some View {}

Concurrency

func listPhotos(inGallery name: String) async throws -> [String] {
    try await Task.sleep(nanoseconds: 2 * 1_000_000_000)  // Two seconds
    return ["IMG001", "IMG99", "IMG0404"]
}

actor TemperatureLogger {}

Error handling

do {
    try nourish(with: "Beet-Flavored Chips")
} catch {
    assertionFailure("No crash in production")
    fatalError("Unexpected non-vending-machine-related error: \(error)")
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.