Skip to content

Instantly share code, notes, and snippets.

@alexdremov
Last active April 19, 2022 07:27
Show Gist options
  • Save alexdremov/5c1b55c35ddf440be3058cc967a3f9f1 to your computer and use it in GitHub Desktop.
Save alexdremov/5c1b55c35ddf440be3058cc967a3f9f1 to your computer and use it in GitHub Desktop.
class Foo {
let bonkProvider: () -> DBConnection
lazy var bonk: DBConnection = bonkProvider()
init(_ expression: @escaping @autoclosure () -> DBConnection) {
self.bonkProvider = expression
}
func send() {
// Here bonkProvider() is called
// only for the first call of send()
bonk.sendMessage()
}
}
func calculate(_ expression: @autoclosure () -> Int,
zero: Bool) -> Int {
guard !zero else {
return 0
}
return expression()
}
calculate(1 + 2, zero: false) // 3
calculate([Int](repeating: 5, count: 10000000).reduce(0, +),
zero: false) // 50000000
calculate([Int](repeating: 5, count: 1000).reduce(0, +),
zero: true) // 0
@dynamicCallable
struct RangeGenerator {
var range: Range<Int>
func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> [Int] {
if args.count > 1 || args.first?.key != "count" {
fatalError("Unknown arguments \(args)")
}
let count = args.first!.value
return (0..<count).map{ _ in Int.random(in: range) }
}
}
let gen = RangeGenerator(range: 0..<100)
print(gen(count: 13))
// [2, 89, 4, 17, 65, 26, 73, 86, 93, 13, 25, 96, 96]
@dynamicMemberLookup
class Foo {
subscript(dynamicMember string: String) -> String {
return string
}
}
let a = Foo()
print(a.helloWorld)
class Bob {
let age = 22
let name = "Bob"
}
@dynamicMemberLookup
class Foo {
let himself = Bob()
subscript<T>(dynamicMember keyPath: KeyPath<Bob, T>) -> T {
return himself[keyPath: keyPath]
}
}
let a = Foo()
print(a.age)
enum API {}
extension API {
static let token = "…"
struct CatsCounter {
}
}
let a = API.CatsCounter()
print(API.token)
struct Foo {
@inlinable
@inline(__always)
func simpleComputation(_ a: Int, _ b: Int) -> Int {
duplicate(a) + duplicate(b)
}
@usableFromInline
func duplicate(_ c: Int) -> Int {
c * 2
}
func general() {
print("Hello world")
}
}
class Foo {
lazy var bonk = DBConnection()
func send() {
bonk.sendMessage()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment