Reputation: 2642
I am working with Swift 5, in Xcode 10.2.1
I have this function inside of an extension of UInt8
The compiler complains in line 5, with Unexpected non-void return value in void function
The return type is properly defined, and if the line return "\(opCode)"
is commented, it works fine, with the return in the last line return "\(OpCode.NOP)
I am using "\(OpCode.NOP)"
to avoid adding another variable to the enum, but is a regular string
The error continues if I change the line to return ""
, so it has nothing to do with the OpCode
enum.
extension UInt8 {
func opCode() -> String {
OpCode.allCases.forEach { opCode in
if self == opCode.uint8 {
return "\(opCode)" //Unexpected non-void return value in void function
//return "" // Error persists
}
}
return "\(OpCode.NOP)"
}
}
Upvotes: 0
Views: 123
Reputation: 100503
You can't return a value inside void return type of the forEach
instead try
extension UInt8 {
func opCode() -> String {
if let item = OpCode.allCases.first(where:{ self == $0.uint8 }) {
return "\(item)"
}
return "\(OpCode.NOP)"
}
}
Upvotes: 1