14 January 2024

Swift Syntax Sample

Sample Swift syntax highlighting using SwiftSnip.

  1. //
  2. // CodeSample.swift
  3. // App
  4. //
  5. // Created by Steven Grosmark on 11/24/19.
  6. //
  7. import Foundation
  8. /*
  9. | multi-line
  10. | comment, with empty lines
  11. | see: https://g-mark.com
  12. */
  13. open class Blah: NSObject {
  14. enum EmbedError: Error {
  15. case invalidUrl
  16. }
  17. override init() {
  18. super.init()
  19. let zap = "a"
  20. var zoob = 213.456 + 3
  21. zoob += 4
  22. print(zap); print(zoob)
  23. }
  24. private var x: Int?
  25. internal let y: Double = 123.456
  26. lazy public var rawString = ##"\\Hello \##(y) \\World"##
  27. /// Handle the embed request.
  28. /// - Parameter req: the request with the url to embed
  29. @discardableResult
  30. final func embed(_ req: Request, completion: @escaping (Int) -> Void) throws -> /* Int */ String {
  31. guard let uri = req.query[String.self, at: "url"], !uri.isEmpty,
  32. let url = URL(string: uri),
  33. let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
  34. (components.scheme == "http" || components.scheme == "https") else {
  35. return "invalid url"
  36. }
  37. #if swift(>=4.2)
  38. // swift 4.2 only code here
  39. #elseif swift(>=3.2)
  40. #warning("message")
  41. #error("message")
  42. #endif
  43. return "embed: \(url)"
  44. }
  45. @MainActor
  46. func foo(these numbers: Int...) { }
  47. struct Donut {
  48. let regex1 = /([^0-9]+)/
  49. let regex2 = #/([^0-9]+)/#
  50. var a: String
  51. mutating func boo() { a = "a" }
  52. }
  53. // MARK: - this is the end
  54. }
  55. actor Fresh {
  56. nonisolated func fresh(
  57. file: StaticString = #file,
  58. function: StaticString = #function,
  59. line: UInt = #line
  60. ) {
  61. }
  62. func foo() async throws {
  63. try await foo()
  64. Task { @MainActor in
  65. try await Task.sleep(for: .seconds(1))
  66. }
  67. }
  68. }
  69. private let sampleCode =
  70. """
  71. func test() {
  72. print("This is a test.")
  73. }
  74. """
  75. private let anotherSample = """
  76. func test() {
  77. print("This is a \((0..<3).map(String.init).joined(separator: ".")).")
  78. // empty line above - but this one is extra long so that I can test word-wrapping in a multiline string.
  79. // Make \
  80. one \
  81. line
  82. }
  83. """
  84. @propertyWrapper
  85. struct Bloated<T> {
  86. var wrappedValue: T
  87. let projectedValue: T
  88. init(wrappedValue: T) {
  89. self.wrappedValue = wrappedValue
  90. self.projectedValue = wrappedValue
  91. }
  92. }
  93. struct Bling {
  94. @Bloated var zed = 42
  95. func exposed() {
  96. _ = $zed
  97. }
  98. func `func`() {
  99. }
  100. }