swift - 将正确的类型传递给 addch() [ncurses, Linux]

标签 swift ncurses

在关注 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。 (简单的 StringUInt 转换尝试将 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/

相关文章:

ios - OpenCV matchShapes() 输出值

c++ - pdcurses/ncurses 中的重叠窗口

c - C 的 panel.h 中的面板堆叠顺序

ios - SwiftUI:列表上的渐变背景

ios - iOS 中的核心数据,索引超出范围

改变颜色定义 ncurses C

haskell - 解释和编译的Haskell之间ncurses的区别?

c - 我如何保证终端具有 NCURSES 的 Unicode/宽字符支持?

ios - 如何使用单元格中的按钮获取 CollectionViewCell 的当前项目?

ios - UIWebView FinishLoad/检测问题