An intersting problem with Swift

Paul Hudson He recently posted a question about Swift Language on twitter,quite interesting

Q1:

All three match - how many ways can you think of to make this true in Swift?

You’ll learn by trying 👍

DT_PFimXcAYZq-Z.jpg

PS:Code or it didn’t happen 😘

My idea is to change the way “get” works

A1:

Several methods have been collected so far

Rewrite ‘==’

Joe Groff

1
2
3
4
func == (a: inout Int, b: Int) -> Bool {
defer { a += 1 }
return ! (a != b)
}

Andy Lee

1
2
3
4
5
6
7
var a = 1
extension Int {
static func == (left: Int, right: Int) -> Bool {
a += 1
return !(left != right)
}
}

Marius Fanu

1
2
3
4
5
extension Int {
static func == (lhs: Int, rhs: Int) -> Bool {
return true
}
}

Nate Cook

1
2
3
4
5
6
7
8
9
10
11
var fakedOut = false
func == (lhs: Double, rhs: Int) -> Bool {
if !fakedOut {
print("All three match!")
fakedOut = true
}
return Int(lhs) == rhs
}
let a = 0.0
let b = 0.0

Using Unicode

Toni Suter

1
2
3
let a = 1 // 'a'
let a = 2 // 'a' + ZERO WIDTH SPACE
let a = 3 // 'a' + ZERO_WIDTH_SPACE + ZERO_WIDTH_SPACE

Other ways

Toni Suter

1
2
3
4
5
6
7
8
enum Foo: ExpressibleByIntergerLiteral {
case bar
init (integerLiteral value: Int) {
self = .bar
}
}
let a = Foo.bar

Toni Suter

1
2
3
4
5
var _a = 0
var a:Int {
_a += 1
return _a
}

Q2:

Lots of folks are using operator overloading, so for them here’s hard mode !😈

DT_XGJLWsAAdXdT.jpg

A2:

Rewrite ‘&&’

John Payne

1
2
3
4
5
6
7
extension Bool {
static func &&(lhs: Bool, rhs: Bool) -> Bool {
return lhs || rhs ? true : false
}
}
let a = 2
let b = 5

Bool

Apollo Zhu

1
2
3
4
5
6
extension Bool: ExpressibleByInterLiteral {
public init (integerLiteral value: Int) {
srlf = value != 0
}
}
let a: Bool = 1, b = 1

If you know more ways, please let me know in the comments below~

Title: An intersting problem with Swift

Author: Tuski

Published: 01/21/2018 - 19:28:55

Updated: 03/05/2018 - 15:02:50

Link: http://www.perphet.com/2018/01/An-intersting-problem-with-Swift/

Protocol: Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) Reprinted please keep the original link and author

Thx F Sup