Last active
August 6, 2017 06:40
-
-
Save mitsuse/856db9164766ff88c380c4508527f5d5 to your computer and use it in GitHub Desktop.
Embed a value into type with lazy-evaluation in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Size { static var value: Int { get } } | |
enum N: Size { static let value = Int(ProcessInfo.processInfo.environment["ARRAY_SIZE_N"]!)! } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let a = [0, 1, 2, 3] | |
let b1 = ["a", "b", "c", "d"] | |
let b2 = ["a", "b", "c", "d", "e"] | |
let c1 = Array(zip(a, b1)) | |
print(c1) // [(0, "a"), (1, "b"), (2, "c"), (3, "d")] | |
let c2 = Array(zip(a, b2)) | |
print(c2) // [(0, "a"), (1, "b"), (2, "c"), (3, "d")] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Size { static var value: Int { get } } | |
enum _4: Size { static let value = 4 } | |
enum _5: Size { static let value = 5 } | |
struct Array<S: Size, Element> { | |
let elements: [Element] | |
init?(_ elements: [Element]) { | |
guard elements.count == S.value else { return nil } | |
self.elements = elements | |
} | |
init?(_ elements: Element...) { | |
self.init(elements) | |
} | |
} | |
func zip<S: Size, E1, E2>(_ a: Array<S, E1>, _ b: Array<S, E2>) -> Array<S, (E1, E2)> { | |
return Array(Swift.Array(zip(a.elements, b.elements)))! | |
} | |
let a = Array<_4, Int>(0, 1, 2, 3)! | |
let b1 = Array<_4, String>("a", "b", "c", "d")! | |
let b2 = Array<_5, String>("a", "b", "c", "d", "e")! | |
let c1 = zip(a, b1) | |
print(c1) // Array<_4, (Int, String)>(elements: [(0, "a"), (1, "b"), (2, "c"), (3, "d")]) | |
// error: cannot convert value of type 'Array<_5, String>' to expected argument type 'Array<_4, String>' | |
// let c2 = zip(a, b2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment