Skip to content

Instantly share code, notes, and snippets.

@pcantrell
Last active July 25, 2019 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcantrell/1ffc0afd56693349bb98cf82d95107a8 to your computer and use it in GitHub Desktop.
Save pcantrell/1ffc0afd56693349bb98cf82d95107a8 to your computer and use it in GitHub Desktop.

Swift Evolution proposals for the three features I covered:

Here's a good (and mildly critical) overview of dynamic member lookup.

Python interop:

Here's the excellent WWDC talk that talks about keypath member lookup, mingled in among many other things. Well worth watching the whole thing!

Python Interop Example

Setup

pip3 install plotly

mkdir python-interop
cd python-interop

swift package init --type executable

Package.swift

import PackageDescription

let package = Package(
    name: "python-interop",
    dependencies: [
        .package(url: "https://github.com/pvieito/PythonKit.git", .branch("master")),
    ],
    targets: [
        .target(
            name: "python-interop",
            dependencies: ["PythonKit"])
    ]
)

main.swift

import PythonKit
import Foundation

func swirlData(size: Int) -> [[Double]] {
  return (0..<size).map { x in
    (0..<size).map { y in
      let x = Double(x) / Double(size) * 2 - 1
      let y = Double(y) / Double(size) * 2 - 1
      let r = hypot(y, x) * 2
      let Θ = atan2(y, x)
      return cos(r * 5 + Θ * 3) * cos(x) * cos(y)
    }
  }
}

let data = swirlData(size: 120)

let plotly = Python.import("plotly.graph_objects")

let countour = plotly.Contour(z: data, line_smoothing: 1)
let fig = plotly.Figure(data: countour)
fig.shoow()

let surface = plotly.Surface(z: data)
let fig2 = plotly.Figure(data: [surface])
fig2.show()

Key Path Member Lookup Example

import Foundation

struct Name {
  var first, last: String
}

@dynamicMemberLookup
struct WriteLogger<T> {
  var value: T

  subscript<U>(dynamicMember keyPath: WritableKeyPath<T, U>) -> U {
    get {
      self.value[keyPath: keyPath]
    }
    set {
      print("New value: \(newValue)")
      self.value[keyPath: keyPath] = newValue
    }
  }

  subscript<U>(dynamicMember member: String) -> String {
    return "Woooot \(member)"
  }
}

var name = WriteLogger(value: Name(first: "Sally", last: "Jones"))
print(name.frist)
name.first = "Ultrasally"
name.last = "the Ultimate"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment