04-枚举

本文介绍了Swift中的枚举(Enum)特性,包括关联值如何为枚举成员存储额外信息,原始值(Raw Values)的使用,包括默认和隐私原始值的规则。此外,还探讨了递归枚举的概念以及枚举在内存布局中的表现。内容旨在帮助理解Swift枚举的高级用法。
摘要由CSDN通过智能技术生成
  • 枚举的基本用法

enum Direction {
   
    case north
    case south
    case east
    case west
}
enum Direction {
   
    case north, south, east, west
}

var dir = Direction.west
dir = Direction.east
dir = .north
print(dir) // north

switch dir {
   
case .north:
    print("north")
case .south:
    print("south")
case .east:
    print("east")
case .west:
    print("west")
}
  • 关联值(Associated Values)

有时将枚举的成员值其他类型的值关联存储在一起, 会非常有用

enum Score {
   
    case points(Int)
    case grade(Character)
}

var score = Score.points(96)
score = .grade("A")
switch score {
   
case let .points(i):
    print(i, "points")
case let .grade(i):
    print("grade", i)
}
// 打印结果:grade A。
// 注意:其实 i 就是 字符串 "A",'let .grade(i)'相当于拿到枚举中 grade 这个成员值与它关联的值 'A'
enum Date {
   
    case digit(year: Int, month: Int, day: Int)
    case string(String)
}

var date 
在EDKII中,可以使用EFI_PCI_IO_PROTOCOL协议来问PCI设备。以下是一个简单的代码示例,用于枚举PCI设备并打印它们的设备ID和厂商ID: ``` #include <Uefi.h> #include <Library/UefiLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Protocol/PciIo.h> EFI_STATUS EnumeratePciDevices() { EFI_STATUS Status; EFI_HANDLE *HandleBuffer; UINTN HandleCount, Index; Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiPciIoProtocolGuid, NULL, &HandleCount, &HandleBuffer); if (EFI_ERROR(Status)) { Print(L"Failed to locate PCI IO protocol: %r\n", Status); return Status; } for (Index = 0; Index < HandleCount; Index++) { EFI_PCI_IO_PROTOCOL *PciIo; UINT16 VendorId, DeviceId; Status = gBS->HandleProtocol(HandleBuffer[Index], &gEfiPciIoProtocolGuid, (VOID **)&PciIo); if (EFI_ERROR(Status)) continue; Status = PciIo->Pci.Read(PciIo, EfiPciIoWidthUint16, 0, offsetof(PCI_DEVICE_HEADER, VendorId), 1, &VendorId); if (EFI_ERROR(Status)) continue; Status = PciIo->Pci.Read(PciIo, EfiPciIoWidthUint16, 0, offsetof(PCI_DEVICE_HEADER, DeviceId), 1, &DeviceId); if (EFI_ERROR(Status)) continue; Print(L"Device %04x:%04x\n", VendorId, DeviceId); } gBS->FreePool(HandleBuffer); return EFI_SUCCESS; } ``` 在此示例中,我们使用gBS->LocateHandleBuffer函数来获取所有PCI IO协议句柄。然后,我们遍历每个句柄并使用gBS->HandleProtocol函数获取PCI IO协议指针。使用PciIo指针,我们可以读取设备ID和厂商ID,并将它们打印到控制台上。 请注意,此示例假定您已经包含了必要的EDKII头文件,并且您的代码将在UEFI固件环境中编译和运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值