不确定如何标记问题。我想从Int值创建一个Int值数组。例如,如果我有1234,我想输出[1,2,3,4],输出为8765 [8,7,6,5]等。函数应如下所示:
private static func formAnArray(_ value: Int) -> [Int] {
// code
}
答案 0 :(得分:1)
您可以将数字转换为String
并将其映射到数组:
private static func formAnArray(_ value: Int) -> [Int] {
return String(value).compactMap { Int(String($0)) }
}
另一种方式(首选大数)是结合使用%
和/
:
private static func formAnArray(_ value: Int) -> [Int] {
var value = value
var result: [Int] = []
while value > 0 {
result.insert(value % 10, at: 0)
value /= 10
}
return result
}
答案 1 :(得分:1)
您可以使用compactMap获取数字并将其转换为int数组
const ModalContext = React.createContext('modal');
export class App extends React.Component {
constructor() {
super();
this.state = {
isModalOpened: false
}
}
toggleModal = (value) => {
this.setState({
isModalOpened: value
})
};
getModalContextValue() {
return {
isModalOpened: this.state.isModalOpened,
toggleModal: this.toggleModal
}
}
render() {
return (
<ModalContext.Provider value={this.getModalContextValue()}>
//your child components
</ModalContext.Provider>
)
}
}