Define a primitive data type: Difference between revisions
Content added Content deleted
(Define a primitive data type en QBasic) |
(Add swift) |
||
Line 2,282: | Line 2,282: | ||
a *= 2 # a=6 |
a *= 2 # a=6 |
||
say a+b # error: class `MyInt` does not match MyInt(12)</lang> |
say a+b # error: class `MyInt` does not match MyInt(12)</lang> |
||
=={{header|Swift}}== |
|||
<lang swift>struct SmallInt { |
|||
var value: Int |
|||
init(value: Int) { |
|||
guard value >= 1 && value <= 10 else { |
|||
fatalError("SmallInts must be in the range [1, 10]") |
|||
} |
|||
self.value = value |
|||
} |
|||
static func +(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value + rhs.value) } |
|||
static func -(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value - rhs.value) } |
|||
static func *(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value * rhs.value) } |
|||
static func /(_ lhs: SmallInt, _ rhs: SmallInt) -> SmallInt { SmallInt(value: lhs.value / rhs.value) } |
|||
} |
|||
extension SmallInt: ExpressibleByIntegerLiteral { |
|||
public init(integerLiteral value: Int) { self.init(value: value) } |
|||
} |
|||
extension SmallInt: CustomStringConvertible { |
|||
public var description: String { "\(value)" } |
|||
} |
|||
let a: SmallInt = 1 |
|||
let b: SmallInt = 9 |
|||
let c: SmallInt = 10 |
|||
let d: SmallInt = 2 |
|||
print(a + b) |
|||
print(c - b) |
|||
print(a * c) |
|||
print(c / d) |
|||
print(a + c)</lang> |
|||
{{out}} |
|||
<pre>10 |
|||
1 |
|||
10 |
|||
5 |
|||
Runner/main.swift:17: Fatal error: SmallInts must be in the range [1, 10] |
|||
Illegal instruction: 4</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |