It says in the type signature in UIKit that UIContentSizeCategory conforms to the Comparable protocol.
The type signature is:
public struct UIContentSizeCategory : RawRepresentable, Equatable, Hashable, Comparable {
public init(rawValue: String)
}
So how come I get this nasty stack trace when I try to compare them?
po UIContentSizeCategory.small < UIContentSizeCategory.medium
error: warning: <EXPR>:12:9: warning: initialization of variable '$__lldb_error_result' was never used; consider replacing with assignment to '_' or removing it
var $__lldb_error_result = __lldb_tmp_error
~~~~^~~~~~~~~~~~~~~~~~~~
_
error: type 'UIContentSizeCategory' does not conform to protocol 'Comparable'
Swift.Comparable:144:24: note: multiple matching functions named '<=' with type '(UIContentSizeCategory, UIContentSizeCategory) -> Bool'
public static func <=(lhs: Self, rhs: Self) -> Bool
^
Swift.<=:10:13: note: candidate exactly matches
public func <=<T>(lhs: T, rhs: T) -> Bool where T : Comparable
^
Swift.<=:1:13: note: candidate exactly matches
public func <=<T>(lhs: T, rhs: T) -> Bool where T : _SwiftNewtypeWrapper, T.RawValue : Comparable
^
Swift.Comparable:151:24: note: multiple matching functions named '>=' with type '(UIContentSizeCategory, UIContentSizeCategory) -> Bool'
public static func >=(lhs: Self, rhs: Self) -> Bool
^
Swift.>=:12:13: note: candidate exactly matches
public func >=<T>(lhs: T, rhs: T) -> Bool where T : Comparable
^
Swift.>=:1:13: note: candidate exactly matches
public func >=<T>(lhs: T, rhs: T) -> Bool where T : _SwiftNewtypeWrapper, T.RawValue : Comparable
^
Swift.Comparable:158:24: note: multiple matching functions named '>' with type '(UIContentSizeCategory, UIContentSizeCategory) -> Bool'
public static func >(lhs: Self, rhs: Self) -> Bool
^
Swift.>:10:13: note: candidate exactly matches
public func ><T>(lhs: T, rhs: T) -> Bool where T : Comparable
^
Swift.>:1:13: note: candidate exactly matches
public func ><T>(lhs: T, rhs: T) -> Bool where T : _SwiftNewtypeWrapper, T.RawValue : Comparable
^
When I try to write my own extension to make UIContentSizeCategory conform to Comparable I get an error that it already conforms.
The goal here is to be able to check if a size is below a certain threshold and clip some text if it is. How do I fix this?
So, although the docs and signature claim conformance, it does not conform.
First time around I tried this:
extension UIContentSizeCategory: Comparable {
static func <(lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
return true
}
static func >(lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
return true
}
}
it threw an error because of the redundant conformance to Comparable
When I tried it without:
extension UIContentSizeCategory {
static func <(lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
return true
}
static func >(lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
return true
}
}
Magic! Works!
Full code (just in case you were wondering):
extension UIContentSizeCategory {
static var orderedSizes: [UIContentSizeCategory] {
return [.extraSmall,
.small,
.accessibilityMedium,
.medium,
.accessibilityLarge,
.large,
.accessibilityExtraLarge,
.extraLarge,
.accessibilityExtraExtraLarge,
.extraExtraLarge,
.extraExtraExtraLarge,
.accessibilityExtraExtraExtraLarge
]
}
static func < (lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
var sizes = orderedSizes
while sizes.contains(lhs) {
sizes.removeFirst()
}
return sizes.contains(rhs)
}
static func > (lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
var sizes = orderedSizes
while sizes.contains(lhs) {
sizes.removeLast()
}
return sizes.contains(rhs)
}
static func <= (lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
guard lhs != rhs else { return true }
return lhs < rhs
}
static func >= (lhs: UIContentSizeCategory, rhs: UIContentSizeCategory) -> Bool {
guard lhs != rhs else { return true }
return lhs > rhs
}
}
Related
I have this function, which return sum of numbers
func sum<T: Numeric>(_ a: T, _ b: T) -> T {
return a + b
}
And I need to improve this function so that also return the concatenation of Strings by this function without overloading. I probe use RangeReplaceableCollection, but i can't use this protocol with Numeric protocol.
For example:
sum(2, 3) -> 5
sum(1.5, 2.4) -> 3.9
sum("abc", "def") -> "abcdef"
To have one generic function for such a case you would need to find a common behavior that could be used as a constraint for a generic Type. In your case, you can do (but you should NOT) this:
DON'T DO THIS
extension String: AdditiveArithmetic {
// some stupid placeholders, as there is no obvious behavior for that :D
public static func - (lhs: String, rhs: String) -> String {
lhs
}
public static var zero: String {
""
}
}
func sum<T: AdditiveArithmetic>(_ a: T, _ b: T) -> T {
a + b
}
print(sum("LOl", "KEK")) // LOLKEK
print(sum(1, 2)) // 3
I would RECOMMEND just to add a new func for that particular case
func sum(_ a: String, _ b: String) -> String {
a + b
}
protocol AddProtocol {
static func +(lhs: Self, rhs: Self) -> Self
}
func add<T: AddProtocol>(num1: T, _ num2: T) -> T {
return num1 + num2
}
extension Int: AddProtocol {
}
extension String: AddProtocol {}
print(add(num1: "Abc", "Xyz"))
print(add(num1: 12, 30))
In the below example,
let value1: Int? = 23
let value2: Int = 20
let answer = value1 + value2 // Compiler warning that + operator cannot be applied to Int? and Int
So I would have to change the code to
if let value1 = value1 {
let answer = value1 + value2
}
How to create an extension for + that supports Optional values as well? In that case it should give nil as output.
What if the operation has multiple operands?
let value1: Int? = 2
let answer = value1 + 3.0
You just have to find the right protocol type to constrain the generic types, really. After that the implementation is trivial:
// plus and minus is supported by AdditiveArithmetic
func +<T: AdditiveArithmetic>(lhs: T?, rhs: T?) -> T? {
return lhs.flatMap { x in rhs.map { y in x + y } }
/* the above is just a more "functional" way of writing
if let x = lhs, let y = rhs {
return x + y
} else {
return nil
}
*/
}
func -<T: AdditiveArithmetic>(lhs: T?, rhs: T?) -> T? {
return lhs.flatMap { x in rhs.map { y in x - y } }
}
// times is supported by Numeric
func *<T: Numeric>(lhs: T?, rhs: T?) -> T? {
return lhs.flatMap { x in rhs.map { y in x * y } }
}
// divide is not supported by a single protocol AFAIK
func /<T: BinaryInteger>(lhs: T?, rhs: T?) -> T? {
return lhs.flatMap { x in rhs.map { y in x / y } }
}
func /<T: FloatingPoint>(lhs: T?, rhs: T?) -> T? {
return lhs.flatMap { x in rhs.map { y in x / y } }
}
To make value1 + 3.0 work, you'd have to do something like this:
func +<T: BinaryInteger, U: FloatingPoint>(lhs: T?, rhs: U?) -> U? {
return lhs.flatMap { x in rhs.map { y in U(x) + y } }
}
But it's usually not a good idea to go against the restrictions put in place. I don't recommend this.
Only pasting solution for addition, but other operators will work analogously (but mind subtract and division, since they are not commutative)
Three reasonable solutions
Global function(s)
Extend existential* (conforming to AdditiveArithmetic) to some new protocol e.g. AdditiveArithmeticOptional
Extend Optional
* Note: you can read about existentials here, e.g. protocol isn't an existential, but a concrete type, e.g. a struct is.
1 Global function(s)
See #Sweepers answer
Note: a global function is a function not implemented on a type (protocol or existential). Swift's zip function is an example
2 Extend existentials to new protocol
public protocol AdditiveArithmeticOptional: AdditiveArithmetic {
static func + (lhs: Self, rhs: Self?) -> Self
}
public extension AdditiveArithmeticOptional {
static func + (lhs: Self, rhs: Self?) -> Self {
guard let value = rhs else { return lhs }
return value + lhs
}
static func + (lhs: Self?, rhs: Self) -> Self {
rhs + lhs
}
}
extension Int8: AdditiveArithmeticOptional {}
extension Int16: AdditiveArithmeticOptional {}
extension Int32: AdditiveArithmeticOptional {}
extension Int64: AdditiveArithmeticOptional {}
extension Int: AdditiveArithmeticOptional {} // same as `Int64` on 64 bit system, same as `Int32` on 32 bit system
extension UInt8: AdditiveArithmeticOptional {}
extension UInt16: AdditiveArithmeticOptional {}
extension UInt32: AdditiveArithmeticOptional {}
extension UInt64: AdditiveArithmeticOptional {}
extension UInt: AdditiveArithmeticOptional {} // same as `UInt64` on 64 bit system, same as `UInt32` on 32 bit system
3 extend Optional
extension Optional where Wrapped: AdditiveArithmetic {
static func + <I>(optional: Self, increment: I) -> I where I: AdditiveArithmetic & ExpressibleByIntegerLiteral, I.IntegerLiteralType == Wrapped {
guard let value = optional else { return increment }
let base = I.init(integerLiteral: value)
return base + increment
}
static func + <I>(increment: I, optional: Self) -> I where I: AdditiveArithmetic & ExpressibleByIntegerLiteral, I.IntegerLiteralType == Wrapped {
optional + increment
}
}
You could create your own custom operator function if you have multiple scenarios where you require arithmetic operations between optionals as follows:
func + (lhs: Int?, rhs: Int?) -> Int {
(lhs ?? 0) + (rhs ?? 0)
}
func + (lhs: Int?, rhs: Int) -> Int {
(lhs ?? 0) + rhs
}
func + (lhs: Int, rhs: Int?) -> Int {
lhs + (rhs ?? 0)
}
Note: Add return keyword if you are using Swift 5 or below.
Update: Upon further investigation and inspiration from the answer of #sweeper following solution seemed more elegant.
func + <T: AdditiveArithmetic>(lhs: T?, rhs: T?) -> T {
(lhs ?? .zero) + (rhs ?? .zero)
}
or if you need a nil when operation was not successful
func + <T: AdditiveArithmetic>(lhs: T?, rhs: T?) -> T? {
lhs.flatMap { lhs in rhs.flatMap { lhs + $0 }}
}
Optionals don't make much sense to be added, a nil value usually represents something went wrong along the way and a value could not be retrieved. It's better to be explicit, and to write the if-let statements. This way you can handle the cases where you end up with nil values.
But if you want to ignore the nils, then you can use the nil coalescing operator:
let value1: Int? = 23
let value2: Int = 20
let answer = (value1 ?? 0) + value2
You are still explicit about the unwrap, but you also have a fallback route in case you want to ignore the nil value. And, maybe even more important, the code transmits its scope in a clear manner. If someone later on stumbles upon your code it will be clear to them what the code does and how it recovers from unexpected situations (nil is an unexpected value in regards to the addition)
I want to use generic protocol type as a function return type like this:
protocol P {
associatedtype T
func get() -> T?
func set(v: T)
}
class C<T>: P {
private var v: T?
func get() -> T? {
return v
}
func set(v: T) {
self.v = v
}
}
class Factory {
func createC<T>() -> P<T> {
return C<T>()
}
}
But this code compile with errors complained:
Cannot specialize non-generic type 'P'
Generic parameter 'T' is not used in function signature
Is there any way to achieve similar function with Swift?
Swift 5.1 supports returning associated types using Opaque type. Using opaque type, your code builds successfully. Ref
protocol P {
associatedtype T
func get() -> T?
func set(v: T)
}
class C<T>: P {
private var v: T?
func get() -> T? {
return v
}
func set(v: T) {
self.v = v
}
}
class Factory {
func createC<T>() -> some P {
return C<T>()
}
The problem is you cannot use the syntax P<T>. P is a protocol, meaning it can't be treated as a generic type (Cannot specialize non-generic type 'P'), even though it may have a given associatedtype.
In fact, because it has an associatedtype, you now can't even use the protocol type itself directly – you can only use it as a generic constraint.
One solution to your problem is to simply change your function signature to createC<T>() -> C<T>, as that's exactly what it returns.
class Factory {
func createC<T>() -> C<T> {
return C<T>()
}
}
I'm not entirely sure what you would gain from having the return type be a protocol here. Presumably your example is just a simplification of your actual code and you want to be able to return an arbitrary instance that conforms to P. In that case, you could use type erasure:
class AnyP<T> : P {
private let _get : () -> T?
private let _set : (T) -> ()
init<U:P where U.T == T>(_ base:U) {
_get = base.get
_set = base.set
}
func get() -> T? {return _get()}
func set(v: T) {_set(v)}
}
class Factory {
func createC<T>() -> AnyP<T> {
return AnyP(C<T>())
}
}
Suppose I want to have a Set of functions or closures. Here's how I would go about it:
typealias HandlerX = () -> ()
static var handlersX = Set<HandlerX>()
This produces the following compiler error:
Type 'HandlerX' (aka '() -> ()') does not conform to protocol 'Hashable'
Is this a dead end?
Yes, this is a dead end. Hashable isn't really your problem; there's no way to decide whether two closures are Equal (which is a base requirement of Hashable).
You can create a wrapper struct for closure
struct Hashed<T>: Hashable {
let value: T
let hash: Int
init(value: T, hash: Int) {
self.value = value
self.hash = hash
}
public func hash(into hasher: inout Hasher) {
hasher.combine(hash)
}
static func == (lhs: Hashed<T>, rhs: Hashed<T>) -> Bool {
lhs.hashValue == rhs.hashValue
}
}
But you need to understand the identity of your closures. For example, it can be the class that created it, or #filename + #line, or always unique with UUID()
Is it possible to overload equivalence (==) operator for a custom class inside that custom class. However I know that it is possible to have this operator overloaded outside class scope. Appreciate any sample code.
Thanks in advance.
Add global functions. For example:
class CustomClass {
var id = "my id"
}
func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs == rhs
}
func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
return !(lhs == rhs)
}
To conform Equatable protocol in Swift 2
class CustomClass: Equatable {
var id = "my id"
}
func ==(left: CustomClass, right: CustomClass) -> Bool {
return left.id == right.id
}
To conform Equatable protocol in Swift 3
class CustomClass {
var id = "my id"
}
extension CustomClass: Equatable {
static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs.id == rhs.id
}
}
No, operators are overloaded using global functions.