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

Swift tests from Highlight.js

Reference: Highlight.js Swift tests

Attributes

@convention(swift)
@objc
@objc(name)

@propertyWrapper
@SomeWrapper(value: 1.0, other: "string", bool: false)
@resultBuilder

@ notAnAttribute

Availability

#available()
#available(iOS 15.0, *)
@available()
@available(iOS 15.0, *)
@available(iOS 14, deprecated: "reason", *)

#unavailable()
#unavailable(iOS 15.0, *)
// not a keyword
@unavailable()
@unavailable(iOS 15.0, *)

Functions

func f1<
  X,
  Y: A,
  // documentation
  Z: B & C<D>
>() where X == Y, Y: A, Z: B & C<D> { }

func < <T>() { }

func f2(_ p: @escaping () throws -> Void) rethrows -> some Collection { }

func f3(
  p1e p1i: inout Int = 5,
  _ p2: (x: Int, y: Int),
  p3: (var: Int, let: Int) throws -> Int,
  p4: Int...
  p5: @attribute String? = "text"
) { }

init<X: A>(_ p: @attribute inout (x: Int, var: Int) = (0, 0)) { }
init?(_ p: @attribute inout (x: Int, var: Int) = (0, 0)) { }
init! (_ p: @attribute inout (x: Int, var: Int) = (0, 0)) { }

subscript<X: A>(_ p: @attribute inout (x: Int, var: Int) = (0, 0))  { }

protocol Comparable: Equatable {

  static func < (lhs: Self, rhs: Self) -> Bool
  static func <= (lhs: Self, rhs: Self) -> Bool
  static func > (lhs: Self, rhs: Self) -> Bool
  static func >= (lhs: Self, rhs: Self) -> Bool
}

Identifiers

`func`
{ $0 + 1 }
value.$wrappedValue

Keywords

Sequence.Protocol Protocol
String.Type Type

String.init init
String.self self

Any Self
(_ name: String)
x as Int
x as? Double
x as! String
x is String
init? init! init
try? try! try
true false nil
fileprivate(set) internal(set) open(set) private(set) public(set)
unowned(safe) unowned(unsafe)
async await
isolated nonisolated

#if
#error("Error")
#endif

x.as(y)
x.for(y)
#notAKeyword

Numbers

1;  10;  999;    0; 00;  000;     08;   019
1_; 1_0; 9_9__9; 0; 0_0; 0_0_0__; 0__8; 01_9

0b0;  0b11;  0b000;  0b010;  0b01011
0b0_; 0b1_1; 0b0_00; 0b01_0; 0b01__0_1__1_

0o77;   0o0; 0o01;  0o777;   0o644
0o7_7_; 0o0; 0o0_1; 0o77__7; 0o6_44__

0x0;  0xa0;   0x7FFF;  0xd3aD
0x0_; 0xa__0; 0x7F_FF; 0xd3_aD__


4.2;  4.20;   88.0;  13.37
4.2_; 4.2__0; 8_8.0; 13_.3_7__

0e10;  0.00e+10;    9e-10;     4.2E10;   40.0E+10;    0e100;   1010e+10
0e1_0; 0.0__0e+1_0; 9_e-1__0_; 4.2_E1_0; 4_0_.0E+1_0; 0e1_0_0; 10_10e+10_

0x0p0;   0x1.ep6;   0xa0p+01;    0x0.7FFp-18;        0xd3aD.B00p9
0x0_P0_; 0x1__.Ep6; 0xa_0p+0__1; 0x0.7__F_F_P-1__8_; 0xd__3_aD.b00__p9


// expressions containing numeric literals
+0
+-1
2-3
-10.magnitude
fn(-5)
0x2.p2

// expressions not containing numeric literals
fn(x0.d);

// pseudo-expressions containing numeric literals
.0
0.

// invalid pseudo-numeric expressions
_0
0b_0
0b02
0B0
0o_0
0o08
0O7
0x_0
0x0G
0X0
1e_1

0b1e1
0o1e1

0x0pA
0x.1p1

Operator declarations

prefix operator +++
postfix operator +++
infix operator +-: AdditionPrecedence

Operators

!true
~x
+1
-1
..<1
...1
0...
a?
a!

a << 1
a<<1
a >> 1
a>>1
a * 1
a*1
a / 1
a/1
a % 1
a%1
a &* 1
a&*1
a & b
a&b
a + 1
a+1
a - 1
a-1
a &+ 1
a&+1
a &- 1
a&-1
a | b
a|b
a ^ b
a^b
0 ..< 1
0..<1
0 ... 1
0...1
a ?? 1
a??1
a < 1
a<1
a <= 1
a<=1
a > 1
a>1
a >= 1
a>=1
a == 1
a==1
a != 1
a!=1
a === b
a===b
a !== b
a!==b
a ~= 1
a~=1
a .== b
a.==b
a .!= b
a.!=b
a .< b
a.<b
a .<= b
a.<=b
a .> b
a.>b
a .>= b
a.>=b
true && false
true&&false
true || false
true||false
a = 1
a=1
a *= 1
a*=1
a /= 1
a/=1
a %= 1
a%=1
a += 1
a+=1
a -= 1
a-=1
a <<= 1
a<<=1
a >>= 1
a>>=1
a &= b
a&=b
a |= b
a|=b
a ^= b
a^=b

Precedence group

precedencegroup MyGroup {
  higherThan: OtherGroup, AnotherGroup
  lowerThan: OtherGroup, AnotherGroup
  assignment: true
  associativity: left
  associativity: right
  associativity: none
}

Strings

"escaped characters \0\\\t\n\r\"\'"
"escaped unicode \u{0}\u{12}\u{345}\u{6789}\u{abcde}\u{fABCDE}\u{F012345}\u{67890abc}"
#"escaped characters \#0\#\\#t\#n\#r\#"\#'"#
#"escaped unicode \#u{0}\#u{12}\#u{345}\#u{6789}\#u{abcde}\#u{fABCDE}\#u{F012345}\#u{67890abc}"#
#"raw characters \0\\\t\n\r\"\'\u{6789}"#
##"escaped characters \##0\##\\##t\##n\##r\##"\##'"##
##"escaped unicode \##u{0}\##u{12}\##u{345}\##u{6789}\##u{abcde}\##u{fABCDE}\##u{F012345}\##u{67890abc}"##
##"raw characters \0\\\t\n\r\"\'\u{6789} \#0\#\\#t\#n\#r\#"\#'\#u{6789}"##
###"escaped characters \###0\###\\###t\###n\###r\###"\###'"###
###"escaped unicode \###u{0}\###u{12}\###u{345}\###u{6789}\###u{abcde}\###u{fABCDE}\###u{F012345}\###u{67890abc}"###
###"raw characters \0\\\t\n\r\"\'\u{6789} \#0\#\\#t\#n\#r\#"\#'\#u{6789} \##0\##\\##t\##n\##r\##"\##'\##u{6789}"###

"""
escaped characters \0\\\t\n\r\"\'
escaped unicode \u{0}\u{12}\u{345}\u{6789}\u{abcde}\u{fABCDE}\u{F012345}\u{67890abc}
"""
#"""
escaped characters \#0\#\\#t\#n\#r\#"\#'
escaped unicode \#u{0}\#u{12}\#u{345}\#u{6789}\#u{abcde}\#u{fABCDE}\#u{F012345}\#u{67890abc}
raw characters \0\\\t\n\r\"\'\u{6789}
"""#
##"""
escaped characters \##0\##\\##t\##n\##r\##"\##'
escaped unicode \##u{0}\##u{12}\##u{345}\##u{6789}\##u{abcde}\##u{fABCDE}\##u{F012345}\##u{67890abc}
raw characters \0\\\t\n\r\"\'\u{6789} \#0\#\\#t\#n\#r\#"\#'\#u{6789}
"""##
###"""
escaped characters \###0\###\\###t\###n\###r\###"\###'
escaped unicode \###u{0}\###u{12}\###u{345}\###u{6789}\###u{abcde}\###u{fABCDE}\###u{F012345}\###u{67890abc}
raw characters \0\\\t\n\r\"\'\u{6789} \#0\#\\#t\#n\#r\#"\#'\#u{6789} \##0\##\\##t\##n\##r\##"\##'\##u{6789}
"""###

"""
escaped newline \   
same line
"""
#"""
escaped newline \#   
same line
"""#
##"""
escaped newline \##   
same line
"""##
###"""
escaped newline \###   
same line
"""###

"interpolation \(x)"
#"interpolation \#(123) raw \(123)"#
##"interpolation \##(1.23) raw \#(1.23) raw \(1.23)"##
###"interpolation \###("string") raw \##("string") raw \#("string") raw \("string")"###

"""
interpolation \($0 + 1)
"""
#"""
interpolation \#(abs(x - 2) as Double)
raw \(abs(x - 2) as Double)
"""#
##"""
interpolation \##(true)
raw \#(true)
raw \(true)
"""##
###"""
interpolation \###("string")
raw \##("string")
raw \#("string")
raw \("string")
"""###

SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            #if os(iOS)
            Text("Hello, world from iOS!")
            #else
            Text("Hello, world!")
            #endif
        }
    }
}

Tuples

(3, "string")
(c: (x: 1, y: 1), z: 1)
(var: Array<Int>, let: Array<Double>)
(_ x: inout Int) throws -> Int
(abs(-2), abs(2))
(x < y, a > b)
($0, $1)
(@escaping (String) -> Void, @autoclosure () -> String) -> String
(
  // x
  x,
  /* y */
  y
)
(let x, var y)
([key: value, key: value])

Type definitions

class TestClass {}
struct TestStruct {}
enum TestEnum {}
actor TestActor {}
extension TestExtension {}
protocol TestProtocol {}

Types

// Simple identifier
Int

// Types from Apple frameworks
CALayer
CGRect
MKMapView
NSView
UIView
XCTest

// ?, !, ..., and & should not be highlighted as operators
Int?
Int!
Int?!
String...
SomeClass & SomeProtocol

// Arrays, dictionaries, and nested types
[String]
Array<String>
[[Int?]]
Array<Array<Int?>>
[String: Int]
Dictionary<String, Int>
Swift.Array<Int>.Element

// Tuples
()
(Double, Double)
(x: Double, y: Double)

// Functions
(@escaping (String) -> Void, @autoclosure () -> String) -> String
(Int, String...) -> some Collection
() throws -> Self

// Generic arguments
Array<String.Type>
Array<Sequence.Protocol>
Dictionary<String, Any>
Dictionary<String, Array<Int>>
Array<(@autoclosure () -> String) throws -> String?>
Array<
  // documentation
  Int
>

Swift tests from Prism.js

Reference: Prism.js Swift tests

Attributes

@IBOutlet
@IBDesignable
@IBAction
@IBInspectable
@class_protocol
@exported
@globalActor
@MainActor
@noreturn
@NSCopying
@NSManaged
@objc
@propertyWrapper
@UIApplicationMain
@auto_closure

@SomeCustomName

Class names

struct SomeStructure {}
enum SomeEnumeration {}
class SomeClass: SomeSuperclass {
    class var overrideableComputedTypeProperty: Int {
        return 107
    }
}

Comments

// foo
/**/
/* foo */
/*
 foo
*/

/*
/*
 foo
*/
*/

Constants (not supported)

nil
AB
FOO_BAR
kAb
kFoo_bar

Directives

#if os(tvOS)
#if !DEBUG && ENABLE_INTERNAL_TOOLS
#if SWIFTUI_PROFILE
#if compiler(>=5)
#if compiler(>=5) && swift(<5)

#elseif compiler(>=5)
#else
#endif

#sourceLocation(file: "foo", line: 42)
#sourceLocation()

#error("error message")
#warning("warning message")

#available(iOS 13, *)

#selector(SomeClass.doSomething(_:))

#keyPath(SomeClass.someProperty)

Functions

func greetAgain(person: String) -> String {
    return "Hello again, " + person + "!"
}
print(greetAgain(person: "Anna"))
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
    // function body goes here
}


// none of the below are functions
subscript(index: Int) -> Int {
    get {}
    set(newValue) {}
}

Keywords

Any
Protocol
Self
Type
actor
as
assignment
associatedtype
associativity
async
await
break;
case
catch
class;
continue;
convenience
default
defer
deinit
didSet
do
dynamic
else
enum
extension
fallthrough
fileprivate
final
for
func;
get
guard
higherThan
if
import
in
indirect
infix
init
inout
internal
is
isolated
lazy
left
let
lowerThan
mutating
none
nonisolated
nonmutating
open
operator
optional
override
postfix
precedencegroup
prefix
private
protocol
public
repeat
required
rethrows
return
right
safe
self
set
some
static
struct
subscript
super
switch
throw
throws
try
typealias
unowned
unsafe
var
weak
where
while
willSet

Labels

gameLoop: while square != finalSquare {
    break gameLoop
    continue gameLoop
}

Literals

#file
#fileID
#filePath
#line
#column
#function
#dsohandle

#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
#fileLiteral(resourceName: "foo")
#imageLiteral(resourceName: "foo")

Numbers

// Checks for decimal, hexadecimal, octal and binary numbers.
42
42_000
3.1415_9
4.2e14
0xBaf_Face
0xFF47.AB_61p2
0b0000_1111
0o147_654

Operators (not supported)

+ - * / %
+= -= *= /= %=

~ & | ^ << >>
~= &= |= ^= <<= >>=

&+ &- &* &<< &>>
&+= &-= &*= &<<= &>>=

=
== != === !== <= >= < >
! && ||

..< ...

->

??

// custom operators
+++
prefix func +++ (vector: inout Vector2D) -> Vector2D {}

// dot operators (SIMD)
.!= .== .< .> .<= .>=

Punctuations

{ } [ ] ( )
; , . :
\

Short arguments

reversedNames = names.sorted(by: { $0 > $1 } )

Strings

""
"fo\"o"
"foo\
bar"

"foo /* not a comment */ bar"
"foo\
/* not a comment */\
bar"

let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

let threeMoreDoubleQuotationMarks = #"""
Here are three more double quotes: """
"""#
#"Write an interpolated string in Swift using \(multiplier)."#


"foo \(42)"
"foo \(f("bar"))"
"\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
#"6 times 7 is \#(6 * 7)."#