Skip to content

Instantly share code, notes, and snippets.

View DecodableWithArrayOfObjects.swift
import Foundation
struct User: Decodable {
var firstName: String
var lastName: String
var pets: [Pet]
struct Pet: Decodable {
var species: String
var breed: String
View CommandLineArguments.swift
func run() {
    let arguments = CommandLine.arguments
    if arguments.count > 1 {
        let greeting = arguments[1]
        print(greeting)
View CommandLine.swift
import Foundation
func run() {
let arguments = CommandLine.arguments
print(arguments)
print("Hello, World! This is my command line tool")
View HelloWorld.swift
import Foundation
print(“Hello, World! This is my command line tool”)
View CompactMap2.swift
let midfielders = ["Barnes", "McManaman", nil, nil, "Gerrard"]
let midField = midfielders.compactMap { $0?.uppercased() }
print(midField)
View FlatMapWithMap.swift
let playersUpper = players.flatMap{ $0.map { $0.uppercased() } }
print(playersUpper)
// Returns ["OWEN", "FOWLER", "RUSH", "BARNES", "MCMANAMAN", "GERRARD", "CARRAGER", "THOMPSON", "NICOL"]
View flatMapFunction.swift
let allPlayers = players.flatMap{ $0.uppercased() }
View FlatMap.swift
let forwards = ["Owen", "Fowler", "Rush"]
let midfielders = ["Barnes", "McManaman", "Gerrard"]
let defenders = ["Carrager", "Thompson", "Nicol"]
let players = [forwards, midfielders, defenders]
let allPlayers = players.flatMap { $0 }
print(allPlayers) // returns ["Owen", "Fowler", "Rush", "Barnes", "McManaman", "Gerrard", "Carrager", "Thompson", "Nicol"]
View CompactMap.swift
let numbers = [1,2,3,4,5,6,7,8,9,10]
let evenNumbers = numbers.compactMap { $0 % 2 == 0 ? $0 : nil }
print(evenNumbers) //returns [2,4,6,8,10]
View MapLoop.swift
let players = ["Gerrard", "Dalglish", "Barnes"]
var playersUppercased = [String]()
for player in players {
playersUppercased.append(player.uppercased())
}
print(playersUppercased) // returns ["GERRARD", "DALGLISH", "BARNES"]
You can’t perform that action at this time.