在关注 tutorial关于如何快速使用 ncurses 我一直面临错误:
main.swift:31:15: error: cannot convert value of type 'UInt?' to expected argument type 'chtype' (aka 'UInt32')
addch(UInt("*"))
^~~~~~~~~
它提示类型,但是当我将其更改为 UInt32 时,错误更改为 error: ambiguous use of 'init' addch(UInt32("*"))
问题
- 如何将正确的值类型传递给 addch?
完整代码供引用:
import Foundation
import CNCURSES
import Glibc
enum Signal:Int32 {
case INT = 2
case WINCH = 28
}
typealias SignalHandler = __sighandler_t
func trap(signum:Signal, action:@escaping SignalHandler) {
signal(signum.rawValue, action)
}
func getmaxyx(window:UnsafeMutablePointer<WINDOW>, y:inout Int32, x:inout Int32) {
x = getmaxx(window)
y = getmaxy(window)
}
func getcuryx(window:UnsafeMutablePointer<WINDOW>, y:inout Int32, x:inout Int32) {
x = getcurx(window)
y = getcury(window)
}
func drawbox(numlines:Int32, numcols:Int32) {
for y in 0...numlines-1 {
for x in 0...numcols {
move(y, x)
if y == 0 || y == numlines-1 {
addch(UInt("*"))
} else {
if x == 0 || x == numcols {
addch(UInt("*"))
}
}
}
}
refresh()
}
[...]
initscr()
noecho()
curs_set(0)
getmaxyx(window:stdscr, y:&maxy, x:&maxx)
drawbox(numlines:maxy, numcols:maxx)
center(text:"Hello world!", numlines:maxy, numcols:maxx)
while true {
select(0, nil, nil, nil, nil)
}
最佳答案
看到错误信息,需要传递一个UInt32
值给addch(_:)
。
UInt("*")
的返回类型是UInt?
,它的实际值总是nil
。 (简单的 String
到 UInt
转换尝试将 String 解释为十进制整数。)
当你想要一个字符编码为UInt32
时,你可能需要这样写:
addch(("*" as UnicodeScalar).value)
如果您的代码有更多的 addch(_:)
调用,您可以为它定义一个简单的包装器。
例如:
func addCh(_ us: UnicodeScalar) {
addch(us.value)
}
addCh("*")
通过显式注释为 UnicodeScalar
,String Literals 被解释为 UnicodeScalar
并且其 value
属性的类型为 UInt32
.
关于swift - 将正确的类型传递给 addch() [ncurses, Linux],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582228/