在 Swift 中,可以使用字符串访问结构属性吗? [英] In Swift, can one use a string to access a struct property?

查看:32
本文介绍了在 Swift 中,可以使用字符串访问结构属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体,我想知道是否可以使用括号语法访问变量.这是我的结构:

I have a struct and I would like to know if I can access variables using bracket syntax. Here is my struct:

import UIKit

public struct Pixel {
    public var value: UInt32
    public var red: UInt8
    public var green: UInt8
    public var blue: UInt8
    public var alpha: UInt8
}

public struct RGBAImage {
    public var pixels: [ImageProcessor_Sources.Pixel]
    public var width: Int
    public var height: Int
    public init?(image: UIImage)
    public func toUIImage() -> UIImage?
}

我想像这样访问变量 pixel["red"],而不是 pixel.red

I would like to access the variable like so pixel["red"], as opposed to pixel.red

var image = RGBAImage(image: image!)!
var pixel = image.pixels[index]
pixel["red"] = 255 // as opposed to pixel.red

有没有办法在 Swift 中做到这一点?

Is there any way to do this in Swift?

推荐答案

我不认为像这样的基于字符串的访问是好的 Swift 风格.vadian 展示了如何做到这一点,但要像这样动态获取和设置成员,最好使用 内置键路径功能::>

I don't think string-based access like this is good Swift style. vadian shows how it can be done, but to dynamically get and set members like this, it would be best to use the built-in keypath functionality:

let redChannel = pixel[keyPath: \.red]
pixel[keyPath: \.green] = 0xB5

另一种选择(在 Swift 4 之前更相关)是使用枚举来定义键:

Another option (more relevant prior to Swift 4) would be to use an enum to define the keys:

enum Component
{
    case red
    case green
    case blue
    case alpha
}

然后调整 vadian 演示的 subscript 函数以接受 Pixel.Component 而不是 String.

Then adapt the subscript function that vadian demonstrated to accept Pixel.Component instead of String.

这有一个显着的优势,您可以不再传递无效的密钥.

This has a significant advantage in that you can no longer pass an invalid key.

根据您的定义:

public extension Pixel
{
    public enum Component
    {
        case red, blue, green, alpha
    }

    public subscript(key: Component) -> UInt8
    {
        get
        {
            switch key {
                case .red: return self.red
                case .green: return self.green
                case .blue: return self.blue
                case .alpha: return self.alpha
            }
        }
        set
        {
            switch key {
                case .red: self.red = newValue
                case .green: self.green = newValue
                case .blue: self.blue = newValue
                case .alpha: self.alpha = newValue
            }
        }
    }
}

<小时>

var pxl = Pixel(value: 0xFEEDFACE, red: 0xFE, green: 0xED, blue: 0xFA, alpha: 0xCE)
let redChannel = pxl[.red]
print(redChannel)
pxl[.green] = 0xB5
print(pxl)

这篇关于在 Swift 中,可以使用字符串访问结构属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆