简体   繁体   English

如何使用需要返回值的“updateTextAttributes(conversionHandler:)”

[英]How can I use "updateTextAttributes(conversionHandler:)" that needs to return a value

Is there anyway to assign this constant a value?无论如何要为这个常量分配一个值?

 let conversionHandler : ([NSAttributedString.Key : Any]) -> [NSAttributedString.Key : Any] =  ...    
// how can I assign 


    if #available(iOS 13.0, *) {
        textView.updateTextAttributes(conversionHandler: conversionHandler)
    } else {

    }
Closure expression syntax has the following general form:

{ (parameters) -> return type in
    statements
}

Solution解决方案

Closure Expression Syntax闭包表达式语法

let conversionHandler : ([NSAttributedString.Key : Any]) -> [NSAttributedString.Key: Any] = { dictionary in
    return dictionary
}

Shorthand Argument Names简写参数名称

Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure's arguments by the names $0, $1, $2, and so on. Swift 自动为内联闭包提供速记参数名称,可用于通过名称 $0、$1、$2 等引用闭包参数的值。

If you use these shorthand argument names within your closure expression, you can omit the closure's argument list from its definition, and the number and type of the shorthand argument names will be inferred from the expected function type.如果你在你的闭包表达式中使用这些速记参数名称,你可以从它的定义中省略闭包的参数列表,并且速记参数名称的数量和类型将从预期的函数类型中推断出来。

let conversionHandler : ([NSAttributedString.Key : Any]) -> [NSAttributedString.Key: Any] = {
    return $0
}

source: https://docs.swift.org/swift-book/LanguageGuide/Closures.html来源: https : //docs.swift.org/swift-book/LanguageGuide/Closures.html

let conversionHandler : ([NSAttributedString.Key : Any]) -> [NSAttributedString.Key: Any] = {_ in 
             let font = UIFont.systemFont(ofSize: 72)
            let attributes: [NSAttributedString.Key: Any] = [
                .font: font,
                .foregroundColor: UIColor.red,
            ]

            return attributes
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM