ios 在 Swift 中如何知道一个数字是奇数还是偶数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24056985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know if a number is odd or even in Swift?
提问by Asif Bilal
I have an array of numbers typed Int.
我输入了一个数字数组Int。
I want to loop through this array and determine if each number is odd or even.
我想遍历这个数组并确定每个数字是奇数还是偶数。
How can I determine if a number is odd or even in Swift?
如何确定一个数字在 Swift 中是奇数还是偶数?
回答by Charith Nidarsha
var myArray = [23, 54, 51, 98, 54, 23, 32];
for myInt: Int in myArray{
if myInt % 2 == 0 {
println("\(myInt) is even number")
} else {
println("\(myInt) is odd number")
}
}
回答by num8er
Use the %Remainder Operator(aka the Modulo Operator) to check if a number is even:
使用%余数运算符(又名模运算符)检查数字是否为偶数:
if yourNumber % 2 == 0 {
// Even Number
} else {
// Odd Number
}
or, use remainder(dividingBy:)to make the same check:
或者,用于remainder(dividingBy:)进行相同的检查:
if yourNumber.remainder(dividingBy: 2) == 0 {
// Even Number
} else {
// Odd Number
}
回答by pkamb
Swift 5 adds the function isMultiple(of:)to the BinaryIntegerprotocol.
Swift 5 将该功能添加isMultiple(of:)到BinaryInteger协议中。
let even = binaryInteger.isMultiple(of: 2)
let odd = !binaryInteger.isMultiple(of: 2)
This function can be used in place of %for odd/even checks.
此函数可用于代替%奇数/偶数检查。
This function was added via the Swift Evolution process:
此功能是通过 Swift Evolution 过程添加的:
- Preliminary Discussion in Swift Forum
- Swift Evolution Proposal
- Accepted Swift Evolution Implementation
Notably, isEvenand isOddwere proposed but notaccepted in the same review:
值得注意的是,isEven和isOdd被提出,但不是在同一个评审接受的:
Given the addition of
isMultiple(of:), the Core Team feels thatisEvenandisOddoffer no substantial advantages overisMultiple(of: 2).Therefore, the proposal is accepted with modifications.
isMultiple(of:)is accepted butisEvenandisOddare rejected.
鉴于添加
isMultiple(of:),核心团队认为isEven并isOdd没有提供比isMultiple(of: 2).因此,该提案经修改后被接受。
isMultiple(of:)被接受,但isEven和isOdd被拒绝。
If desired, those methods can be added easily through extension:
如果需要,可以通过扩展轻松添加这些方法:
extension BinaryInteger {
var isEven: Bool { isMultiple(of: 2) }
var isOdd: Bool { !isEven }
}
回答by pkamb
"Parity" is the name for the mathematical concept of Odd and Even:
“Parity”是奇数和偶数的数学概念的名称:
You can extend the Swift BinaryIntegerprotocol to include a parityenumeration value:
您可以扩展 SwiftBinaryInteger协议以包含parity枚举值:
enum Parity {
case even, odd
init<T>(_ integer: T) where T : BinaryInteger {
self = integer.isMultiple(of: 2) ? .even : .odd
}
}
extension BinaryInteger {
var parity: Parity { Parity(self) }
}
which enables you to switchon an integer and elegantly handle the two cases:
这使您能够switch使用整数并优雅地处理两种情况:
switch 42.parity {
case .even:
print("Even Number")
case .odd:
print("Odd Number")
}

