Skip to content

Commit

Permalink
TypePathConvertible: add a simple type path extension (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
melle committed Mar 9, 2023
1 parent 079dcc3 commit 0aa9050
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Sources/FoundationExtensions/Utils/TypePathConvertible.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved.

import Foundation

/// Allows to turn the Type-hierarchy into a string, i.e. "`Superclass.Subclass`".
public protocol TypePathConvertible {
var typePath: String { get }
}

extension TypePathConvertible {
public var typePath: String {
let reflectionString = String(reflecting: self)

// Regex: "\.\([^\)]*\)" matches .("anything but a closing brace")
guard let regex = try? NSRegularExpression(pattern: "\\.\\([^\\)]*\\)", options: NSRegularExpression.Options.caseInsensitive) else {
return String(describing: self)
}
// Remove anonymous types that appear in unit testing, i.e. "A.B.C.(unknown context at $1071608c4).(unknown context at $107160918).yak"
return regex.stringByReplacingMatches(in: reflectionString,
options: [],
range: NSMakeRange(0, reflectionString.count),
withTemplate: "")
}
}
30 changes: 30 additions & 0 deletions Tests/FoundationExtensionsTests/TypePathConvertibleTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright © 2023 Lautsprecher Teufel GmbH. All rights reserved.

import Foundation
import FoundationExtensions
import XCTest

class TypePathConvertibleTests: XCTestCase {

func testTypePath() {
// given
enum A: TypePathConvertible {
enum B: TypePathConvertible {
case foo
case bar

enum C: TypePathConvertible {
case yik
case yak
}
}
}
let sut = A.B.C.yak

// when
let result = sut.typePath

// then
XCTAssertEqual(result, "FoundationExtensionsTests.TypePathConvertibleTests.A.B.C.yak")
}
}

0 comments on commit 0aa9050

Please sign in to comment.