1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
|
import Foundation
@testable import MyModule
func sayHello(person:String) -> String {
return "Hello, \(capitalize(word:person)). \"How're are you doin\'?\""
}
func capitalize(#word:String) -> String {
//TODO: test this
return word.capitalizedString
}
sayHello("Toto")
var pi = 3.1415
var foo = cast as SomeType
var foo = optionalCast as? SomeType
var foo = forcedCast as! SomeType
func halfOpenRangeLength(start:Int, end:Int) -> Int {
return end - start
}
halfOpenRangeLength(3, 8)
if let var = option {
if more && complex, let optional = binding, example = here where option.foo == example.foo {
// things
}
}
func count(string:String) -> (vowels:Int, consonants:Int, others:Int) {
var vowels = 0, consonants = 0, emoji = 0, whitespace = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a","o","i","u","e":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
//TODO: Add more emoji
case "\u{1F604}":
++emoji
case "\n", "\r", "\t", "\0", "\u{A0}", "\u{205F}":
++whitespace
default:
++others
}
}
return (vowels,consonants,others)
}
count(sayHello("John"))
// Unicode and Emoji support
let 😄face = "Happy Face"
let ქართულადაც = "This is Georgian"
let こんにちは = "...and Japanese"
let 𓂀 = "and hieroglyphs"
// Integer Literals
let decimalInteger = 1234567
let decimalIntegerWithGroupings = 1_234_567
let hexadecimalInteger = 0xABCDEF
let octalInteger = 0o0644
let binaryInteger = 0b1010
// Floating-Point Literals
let decimalFloatingPoint = 1234567.89
let decimalFloatingPointWithGroupings = 1_2345_67.89
let hexadecimalFloatingPoint = 0xA.1p-3
// String Literals
let string = "Hello, world!"
let multilineString = """
All human beings are born free and equal in dignity and rights.
They are endowed with reason and conscience
and should act towards one another in a spirit of brotherhood.
"""
func join(#firstString:String,#secondString:String,joiner:String = " & ") -> String {
return "\(firstString)\(joiner)\(secondString)"
}
join(firstString: "Toto", secondString: "Someone Other", joiner: " + ")
func alignedRight(inout #string:String, count:Int, pad:Character) -> String {
let amountToPad = count - countElements(string)
for _ in 1...amountToPad {
string = pad + string
}
return string;
}
/* This is a multiline comment
/*
This part is nested into the parent comment
*/
Trailing part of parent comment
*/
let thisIsNotAComment = true
/* Singleline Comment */
var textToAlign = "Toto"
alignedRight(string: &textToAlign, 10, "-")
textToAlign
//MARK: Function Types
func addToInts(a:Int,b:Int) -> Int {
return a + b
}
let addNumbers: (Int,Int)->(Int) = addToInts;
addNumbers(3,2)
func printMathProblem(mathFunction:(Int,Int)->Int,a:Int,b:Int)->String {
return "Result " + String(mathFunction(a,b))
}
printMathProblem(addNumbers, 5, 10)
// Function return types + Nested Functions
func chooseSteperFunction(backward:Bool) -> (Int) -> Int {
func stepForward(input:Int)->Int {
return input + 1
}
func stepBackward(input:Int)->Int {
return input + 1
}
return backward ? stepBackward : stepForward
}
let currentValue = 5
chooseSteperFunction(currentValue > 0)(currentValue)
// Closures
func comparator(s1:String,s2:String)->Bool {
return s2 > s1
}
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let revised = sorted(names, comparator)
let revised2 = sorted(names, {
(s1:String,s2:String)->Bool in
return s2 > s1
})
let revised3 = sorted(names, { s1, s2 in s1 > s2 })
revised3
let revised4 = sorted(names) { $0 > $1 } // This is also a trailing closure
revised4
let revised5 = sorted(names, >)
// Long closures
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
strings
// Closure Value Capturing
func makeIncrementor(firstNumber number:Int) -> () -> Int
{
var runningTotal = 0
func incrementor()->Int {
runningTotal += number
return runningTotal
}
return incrementor
}
let incrementor = makeIncrementor(firstNumber: 4)
incrementor()
// @autoclosure
func simpleAssert(@autoclosure condition: () -> Bool, message: String = "Assertion failed") {
if !condition() {
println(message)
}
}
func lazyAssertion(@autoclosure(escaping) condition: () -> Bool, message: String = "") {
lazyAssertions.append(condition)
}
func autoreleasepool(@noescape code: () -> ()) {
pushAutoreleasePool()
code()
popAutoreleasePool()
}
// optional function call
let maybeFunction: (() -> ())? = nil
maybeFunction?()
maybeFunction!()
// Swift 2 exceptions
func throwingFunction() throws -> String {
throw ErrorType.Error
}
do {
try throwingFunction()
} catch {
println(error)
}
try! throwingFunction()
func rethrowingFunction(f: T throws -> U) rethrows -> U {}
// other swift 2 stuff
guard let x = optionalValue else {
print("Fail")
throw NSError(domain: "", code: 0, userInfo: nil)
}
defer { callback() }
if case let x? = optionalValue {print("Unwrapped: \(x)")}
repeat {
// loop…
} while condition
if #available(iOS 8.0, OSX 10.10, *) {
// Use Handoff APIs when available.
let activity = NSUserActivity(activityType:"com.example.ShoppingList.view")
} else if #unavailable(linux) {
// Fall back when Handoff APIs not available.
} else {
}
//MARK: Classes
public class Person : NSObject {
let firstName: String
private var lastName: String
private(set) var age: Int {
didSet {
println("Happy Birthday")
}
}
internal(set) var doubleAge = 0.0
unowned(safe) var safeUnowned = nil
unowned(unsafe) var unsafeUnowned = nil
lazy var phoneNumbers = [String]()
@NSCopying var modificationDate: NSDate = NSDate()
required public init(name: String, age: Int) {
self.name = name
self.age = age
super.init()
}
internal var isAdmin: Bool { return false }
final func doSomething() {
//TODO: Do something
}
dynamic func somethingDynamic() { }
}
@objc(MYCustomView) class CustomView: NSView, SomeProtocol , OtherProtocol {
@IBOutlet var button: AnyObject!
@IBAction func doSomething(sender: AnyObject) {
//TODO: Do something
}
}
//MARK: Protocols
@objc protocol Random {
typealias T: SomeConstraint
func random() -> Self
optional func seed(seed: Int)
required func foo()
}
extension SomeProtocol where T: OtherProtocol {
func blah() {
// default implementation
}
}
extension SomeClass {
}
struct Stack<T, U>: Equatable {
var items = [T]()
}
typealias Speed = Double
enum State: Equatable {
case Stopped, Paused
case Running(Speed)
}
@availability(OSX, introduced=10.10) func localizedCaseInsensitiveContainsString(aString: String) -> Bool
//MARK: Conditional compilation
#if os(iOS)
sayHello("iOS")
#if arch(arm)
typealias View = UIView
#elseif arch(arm64)
typealias View = UIView64
#else
#warning("Unknown architecture")
#endif
#elseif os(OSX)
/* Uncomment this when the Mac goes 64bit
#if arch(i386)
typealias View = NSView
#elseif arch(x86_64)
typealias View = NSView64
#endif
*/
#endif
protocol Protocol {
associatedtype AssociatedType
typealias TypeAlias
}
// keywords acceptable as argument names now:
NSURLProtectionSpace(host: "somedomain.com", port: 443, protocol: "https", realm: "Some Domain", authenticationMethod: "Basic")
let fn1 = someView.insertSubview(_:at:)
let fn2 = someView.insertSubview(_:aboveSubview:)
#if swift(>=2.2) || os(macOS)
func foo(x: Int) -> (y: Int) -> () {}
#else
func foo(x: Int)(y: Int) {}
#endif
let sel = foo(#selector(insertSubview(_:aboveSubview:)))
open class SubclassableParentClass {
public var size : Int
public func foo() {}
open func bar() {}
public final func baz() {}
private func a() {}
fileprivate func b() {}
}
public final class FinalClass { }
if case let x = a, case let y = b {
func firstFunc(x: A & B) {
let a : A & B & C = Foo()
}
}
func anyCommonElements<T : SequenceType, U : SequenceType>(lhs: T, _ rhs: U) -> Bool where
T.Generator.Element: Equatable,
T.Generator.Element == U.Generator.Element
{
let firstNameGetter = #selector(getter: Person.firstName)
let firstNameSetter = #selector(setter: Person.firstName)
chris.valueForKeyPath(#keyPath(Person.bestFriend.lastName)) // => Groff
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
particleSystem.imageSequenceAnimationMode = SCNParticleImageSequenceAnimationMode.repeat
}
typealias StringDictionary<T> = Dictionary<String, T>
@available(*, unavailable, renamed: "MyRenamedProtocol")
@discardableResult func f() -> T {}
_ = #sourceLocation(file: "foo", line: 42)
@available(swift, obsoleted: 5.0.0, renamed: "foo2(file:line:)")
func foo(_ file: StaticString = #file, line: UInt = #line) { }
precedencegroup ComparisonPrecedence {
associativity: left
higherThan: LogicalConjunctionPrecedence
lowerThan: Additive
}
infix operator <> : ComparisonPrecedence
// keyword as identifier
var `var` = 3
// keypath
let keypath = \Person.firstName
var keyPath: KeyPath<String, Bool> = \.isEmpty
// tuple destructuring
let (t1, t2) = (1, 2)
var ((`func`, foo), `protocol`) = ((3, 4), 5)
var ( t3 , /* comment */
( t4 , t5 ) ) = ("a", ("b", "c"))
// function with lambda argument
func funcWithLambdaArg(_ fn: (Int) -> Int) -> Int {
return fn(1)
}
funcWithLambdaArg { x in x + 5 }
funcWithLambdaArg { $0 + 5 }
funcWithLambdaArg({ x in x + 5 })
func newView() -> some View {
ViewRegistry.find(\.MyView.name)
}
@frozen
public enum Types {
case a, b, c
case d
}
func test(t: Types?) -> Bool {
switch t {
case .a?: return true
case .b?: return true
case .c: return true
default: return false
}
}
distributed actor AnActor {
nonisolated func funcA() {}
func funcB(otherActor: isolated AnActor) async {
await otherActor.funcB()
async let v = funcA()
}
}
func existential(arg: any Proto1) -> some Proto2 {
autoreleasepool {
}
}
func pwrap() -> Bool {
@SmallNum var myNum: Int = 8
self.$myOwnNum = 8
return $myNum
}
let res = [
// comment not a regex
#//#, // empty regex
##//##, // another
##//#, // unbalanced #
#//##, // unbalanced #
/ not a regex /,
/a regex/,
/not a single-line
regex/,
/re with \/ escaped/,
##/usr/lib/#modules/vmlinuz/##, // unescaped / with ##
/(#*)/(?!\s)[^\n]*(?<![\s\\])/\1/,
#/
multiline regex
/#,
##/
multiline # comment
/#
/###
still going
/##
]
package struct FileDescriptor: ~Copyable {
private var fd: Int32
consuming func close() throws {
discard self
}
}
func makePairs<each First, each Second>(
firsts first: repeat each First,
seconds second: repeat each Second
) -> (repeat Pair<each First, each Second>) {
return (repeat Pair(each first, each second))
}
@freestanding(expression)
public macro stringify<T>(_ value: T) -> (T, String) = #externalMacro(module: "m", type: "t")
let p = #stringify(x + y)
foo() // end-of-file comment
|