Perl 6中的枚举或符号

时间:2015-10-03 01:42:53

标签: perl perl6

我想将参数传递给可能只有预定义值的方法。

extension NSImage {

    static func desktopPicture() -> NSImage {

        let windows = CGWindowListCopyWindowInfo(
            CGWindowListOption.OptionOnScreenOnly,
            CGWindowID(0))! as NSArray

        var index = 0
        for var i = 0; i < windows.count; i++  {
            let window = windows[i]

            // we need windows owned by Dock
            let owner = window["kCGWindowOwnerName"] as! String
            if owner != "Dock" {
                continue
            }

            // we need windows named like "Desktop Picture %"
            let name = window["kCGWindowName"] as! String
            if !name.hasPrefix("Desktop Picture") {
                continue
            }

            // wee need the one which belongs to the current screen
            let bounds = window["kCGWindowBounds"] as! NSDictionary
            let x = bounds["X"] as! CGFloat
            if x == NSScreen.mainScreen()!.frame.origin.x {
                index = window["kCGWindowNumber"] as! Int
                break
            }
        }

        let cgImage = CGWindowListCreateImage(
            CGRectZero,
            CGWindowListOption(arrayLiteral: CGWindowListOption.OptionIncludingWindow),
            CGWindowID(index),
            CGWindowImageOption.Default)!

        let image = NSImage(CGImage: cgImage, size: NSScreen.mainScreen()!.frame.size)
        return image
    }
}

我应该创建一个枚举来传递{{1}}吗?如果是,那怎么样?

或者Perl 6在Ruby中有类似符号的东西吗?

1 个答案:

答案 0 :(得分:3)

正如@Christoph所说,你可以使用枚举:

enum Method <GET PUT POST>;
sub http-send(str $url, Method $m) { * }

http-send("http://url/", GET);

您还可以使用类型约束:

sub http-send(str $url, str $m where { $m ∈ <GET HEAD POST> }) { * }

http-send("http://url/", 'GET');

http-send("http://url/", 'PUT');
Constraint type check failed for parameter '$m'

我猜你也可以使用多调度:

multi sub http-send('GET') { * }
multi sub http-send('PUT') { * }
multi sub http-send($m) { die "Method {$m} not supported." }

http-send('GET');

http-send('POST');
Method POST not supported.