Skip to content

Instantly share code, notes, and snippets.

@23inhouse
Last active February 11, 2021 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 23inhouse/835ba8ebe8117078069420bc407e1d7a to your computer and use it in GitHub Desktop.
Save 23inhouse/835ba8ebe8117078069420bc407e1d7a to your computer and use it in GitHub Desktop.
Swift refactoring
// TL;DR: look at this cool thing in swift
let ibsTags = try ibsTagRecords().reduce(into: [Int64: [Int64]]()) {
// this line here
$0[$1.ibsID, default: []].append($1.tagID)
}
// V1 original
if $0[$1.ibsID] == nil {
$0[$1.ibsID] = [$1.tagID]
} else {
$0[$1.ibsID]?.append($1.tagID)
}
// V2 better than ruby's ||=
if $0[$1.ibsID]?.append($1.tagID) == nil {
$0[$1.ibsID] = [$1.tagID]
}
// v3 the ultimate in readablity in only the way swift can
if $0[$1.ibsID]?.append($1.tagID) == nil { $0[$1.ibsID] = [$1.tagID] }
// v4 or the swift way
$0[$1.ibsID, default: []].append($1.tagID)
// This is the old way pre swift 4.1
$0[$1.ibsID] = ($0[$1.ibsID] ?? []) + $1.tagID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment