在for循环内增加UInt8类型的变量

时间:2016-02-01 07:17:55

标签: swift

import Foundation
import Swift

var buff = [UInt8](count: 256, repeatedValue: 0)
var index: UInt8
index = 0

for var i = 0; i < 256; ++i {
buff[i] = index;
++index
}

当我在for循环之外增加索引时,它可以正常工作。但是当我在for循环中增加索引时,就像在上面的代码中一样,我得到以下错误

1
0  swift                    0x000000010ea31fbb llvm::sys::PrintStackTrace(__sFILE*) + 43
1  swift                    0x000000010ea326fb SignalHandler(int) + 379
2  libsystem_platform.dylib 0x00007fff832c3eaa _sigtramp + 26
3  libsystem_platform.dylib 000000000000000000 _sigtramp + 2094252400
4  swift                    0x000000010cfa09bf llvm::MCJIT::runFunction(llvm::Function*, std::__1::vector<llvm::GenericValue, std::__1::allocator<llvm::GenericValue> > const&) + 271
5  swift                    0x000000010cfa30f6 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1190
6  swift                    0x000000010ce34d8c swift::RunImmediately(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) + 2188
7  swift                    0x000000010cb23151 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&) + 13425
8  swift                    0x000000010cb1fad3 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 2691
9  swift                    0x000000010cb1c154 main + 2324
10 libdyld.dylib            0x00007fff975535ad start + 1
11 libdyld.dylib            0x000000000000000c start + 1756023392
Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -interpret File.swift -target x86_64-apple-darwin15.2.0 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -color-diagnostics -module-name File 
Illegal instruction: 4

任何人都知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

当你尝试增加它时,它在最后一个循环中的问题会溢出你的UInt8.max 255。

您有许多不同的选择可以完成您想要的任务:

要保持循环,您需要从数组中的第二个元素开始迭代,并在将其分配给buff时同时增加var,以防止溢出:

<div id="map-canvas"> ... the map is here ... </div>
<div id="map-key"> ... I made a key for the map </div>

或使用for var i = 1; i < 256; ++i { buff[i] = ++index } 循环来迭代数组索引:

for in

或者您可以使用范围简单地初始化数组:

for i in buff.indices {
    buff[i] = UInt8(i)
}
相关问题