【问题标题】:can´t read this closure in Swift无法在 Swift 中读取此闭包
【发布时间】:2016-04-05 05:00:32
【问题描述】:

我有这个闭包(我在这里有很多 THX 到 dfri!)并且不知道如何转换它:

let attributesOverRanges = fooAttrString.getAttributes()
for (rng, attributes) in attributesOverRanges {
    print("Attributes over range \(rng):")
    attributes.forEach { print("\t\($0.0) = \($0.1)") }
}

这是一些结果行:

Attributes over range (0,12):
    NSFont == <UICTFont: 0x7fc7f2d31330> font-family: "Helvetica Neue";    
font-weight: bold; font-style: normal; font-size: 17.00pt

现在我必须得到信息

  1. NSRange
  2. NSFont
  3. 字体系列:“Helvetica Neue”;字体粗细:粗体;字体样式:正常;字体大小:17.00pt

并将其放入数组/字典中。我尝试了很多,但我无法解决这个问题,感觉就像我似乎是绝对的纽比(英语很糟糕)! :-(

你能帮帮我吗

在@rickster 的回答之后,我尝试使用粗体字体。但我得到一个错误,因为 let value = $0.0 不检索字符串而是字体。我可以将字体转换为字符串吗???我必须在字符串中找到“粗体”。或者你知道另一种检查粗体的方法

let attributesOverRanges = fooAttrString.getAttributes()
var newAttributes: [(NSRange, String)] = []
for (rng, attributes) in attributesOverRanges {
    attributes.forEach {
        let value = $0.0
        if value.contains("font-weight: bold") {    // ERROR
            newAttributes.append((rng, "Bold"))
        }
    }
    print(newAttributes)
}

【问题讨论】:

    标签: xcode swift dictionary closures


    【解决方案1】:

    forEach 是一种对所有序列类型进行迭代的方法——它是for-in 循环的函数式编程版本。传递给forEach 的闭包采用一个参数,即正在检查的序列的当前元素。 (例如,在[1,2,3].forEach { /*...*/ } 中,闭包参数是一个整数。在编写闭包的最简写形式中,您可以将参数称为$0,因此在此示例中您可以为闭包编写{ print($0) } .)

    在您的代码中,attributes 是一个字典。当您遍历字典时,元素类型是 (key, value) 元组。处理元组中项目的最短/标签无关方法是按索引:foo.0foo.1 等。

    将它们放在一起:在您的 forEach 闭包中,$0.0 是您的 attributes 字典中的键,$0.1 是对应的值。

    由于您使用的是 NSAttributedString 的属性字典,因此键是属性名称("NSFont"NSFontAttributeName 常量的值),值是与该键对应的任何对象类型(在此例如,NSFont 实例——您看到的打印内容是您通过询问 description 获得的字体摘要。

    您可以将它们用作另一个字典中的键值对 (otherDict[$0.0] = $0.1),或者只使用数组中的值,因为可能不需要保留 "NSFont" 字符串 (myArray.append($0.1)) .


    找出NSFont 实例是否代表粗体字体实际上并不是一个简单的问题。请记住,许多字体都有wide variety of weights——通常,字体设计者会给超过某个阈值的权重一个标签,在语义上将它们标识为“粗体”,但并非总是如此。

    NSFont 有一个配套 API NSFontDescriptor,可以让您获得一些语义信息。以下是获取该信息的方法以及您的其他信息,但您需要对其进行调整以适应您的情况:

    for (rng, attributes) in attributesOverRanges {
        print("NSRange: \(rng) - has attributes:")
        for (name, value) in attributes {
            if name == NSFontAttributeName {
                if let font = value as? NSFont {
                    print("font name (use with `NSFont(name:size:)`): \(font.fontName)")
    
                    let isBold = font.fontDescriptor.symbolicTraits & UInt32(NSFontBoldTrait) != 0
                    print("is bold font: \(isBold)")
                }
            }
        }
    }
    

    【讨论】:

    • 感谢您的扩展声明@rickster 我如何用您的方式检查它是否是粗体?
    猜你喜欢
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多