Swi Interview Questions
var temp: Temperature = 60.5
Yes, Swi specifies protocols that allow you to use the assignment operator to
initialize a type with literal values. Literal initialization of a certain type is possible by
adopting the corresponding protocol and supplying a public initializer. You
implement ExpressibleByFloatLiteral as follows in the example of Temperature:
extension Temperature: ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(temp: value)
}
}
A er this, we can do the above-given initialization without any errors.
41. To conduct arithmetic or logic tasks, Swi offers a
collection of predefined operators. It also enables for the
construction of bespoke unary and binary operators.
Define and implement a custom power ^^ operator that satisfies the following
requirements:
As arguments, it accepts two Ints.
The first parameter is returned a er raising it to the second parameter's
power.
The equation is correctly evaluated using the conventional algebraic
sequence of operations.
Overflow errors are not taken into account.
There are two steps to creating a new custom operator:
Page 33
© Copyright by Interviewbit
Swi Interview Questions
Declaration: The "operator" keyword is used in the declaration to indicate the
type of the operator (unary or binary), the sequence of letters that make up the
operator, associativity, and precedence. The operator here is ^^ and the type is
infix (binary) in this case. Equal precedence operators ^^ should evaluate the
equation from right to le (associativity is right). The following is the declaration
step:
precedencegroup ExponentPrecedence {
higherThan: MultiplicationPrecedence
associativity: right
}
infix operator ^^: ExponentPrecedence
Implementation: In Swi , there is no set precedence for exponential
operations. Exponents should be calculated before multiplication and division in
the normal algebra sequence of operations. As a result, you will need to set
custom precedence that puts them ahead of multiplication. The following is the
implementation step:
func ^^(base: Int, exponent: Int) -> Int {
let left = Double(base)
let right = Double(exponent)
let powerValue = pow(left, right)
return Int(powerValue)
}
It can be noted that as the program does not take overflows into consideration, in
the event of the operation producing a result that Int can't represent, for example, a
value more than Int.max, then a runtime error occurs.
Do'stlaringiz bilan baham: