I apologise for the poor title, any changes are welcomed.
I have a function that checks the mounted external drives and prints them, that works perfectly, as the for loop loops printing each item out.
I want it to also return these drives concatenated as a string or an array. The problem is while it will print them all perfectly, it will only return the last item (as this is obviously the one left when the loop finished.
Any help getting it to return all mounted disks (not just the last one) would be wonderful.
func checkMountedDrives() -> String
{
var volumeURLString = "unkmown"
if let session = DASessionCreate(kCFAllocatorDefault) {
let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)!
for volumeURL in mountedVolumeURLs {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volumeURL as CFURL),
let bsdName = DADiskGetBSDName(disk) {
let bsdString = String(cString : bsdName)
print("đź’ľvolumes ", volumeURL.path)
volumeURLString = String(volumeURL.path)
}
}
}
return volumeURLString // this only returns the last item, I want them all!
}
Any help for a new (and very old) programmer would be gratefully recieved.
>Solution :
func checkMountedDrives() -> [String]
{
var volumeURLString:[String] = []
if let session = DASessionCreate(kCFAllocatorDefault) {
let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)!
for volumeURL in mountedVolumeURLs {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volumeURL as CFURL),
let bsdName = DADiskGetBSDName(disk) {
let bsdString = String(cString : bsdName)
print("đź’ľvolumes ", volumeURL.path)
volumeURLString.append(String(volumeURL.path))
}
}
}
return volumeURLString // this is all!
}
if you want both bsd and volume then make struct
struct BSDVolume {
let bsd:String
let volume:String
}
func checkMountedDrives() -> [BSDVolume]
{
var bsdVolume:[BSDVolume] = []
if let session = DASessionCreate(kCFAllocatorDefault) {
let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)!
for volumeURL in mountedVolumeURLs {
if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volumeURL as CFURL),
let bsdName = DADiskGetBSDName(disk) {
let bsdString = String(cString : bsdName)
print("đź’ľvolumes ", volumeURL.path)
bsdVolume.append(BSDVolume(bsd: bsdString,volume: String(volumeURL.path))
}
}
}
return bsdVolume // this is all!
}
print(checkMountedDrives().map({$0.bsd})) // all bsd
print(checkMountedDrives().map({$0.volume})) // all volume