diff --git a/Sources/SwiftNetCDF/AttributeProvidable.swift b/Sources/SwiftNetCDF/AttributeProvidable.swift index 5b93034..71c9948 100644 --- a/Sources/SwiftNetCDF/AttributeProvidable.swift +++ b/Sources/SwiftNetCDF/AttributeProvidable.swift @@ -37,11 +37,14 @@ extension AttributeProvidable { try setAttribute(name, [value]) } - /// Define a new attribute by name. The value must be a supported external type. - public func setAttribute(_ name: String, _ value: [T]) throws { - let type = T.netcdfType.typeId + /// Define a new attribute by name. The value must be a supported external type. The type parameter can be set to enfore + public func setAttribute(_ name: String, _ value: [T], type: ExternalDataType = T.netcdfType) throws { + guard T.canRead(type: type) else { + throw NetCDFError.datatypeNotCompatible + } + try T.withPointer(to: value) { ptr in - try setAttributeRaw(name: name, type: type, length: value.count, ptr: ptr) + try setAttributeRaw(name: name, type: type.typeId, length: value.count, ptr: ptr) } } diff --git a/Sources/SwiftNetCDF/Error.swift b/Sources/SwiftNetCDF/Error.swift index 36b6e31..e82a758 100644 --- a/Sources/SwiftNetCDF/Error.swift +++ b/Sources/SwiftNetCDF/Error.swift @@ -33,6 +33,7 @@ public enum NetCDFError: Error { case hdf5Error case netCDF4MetedataError case alreadyExists + case datatypeNotCompatible /// Init from NetCDF error code /// TODO find NetCDF definiton for code 2 "no such file" diff --git a/Tests/SwiftNetCDFTests/SwiftNetCDFTests.swift b/Tests/SwiftNetCDFTests/SwiftNetCDFTests.swift index a304d33..e8b99da 100644 --- a/Tests/SwiftNetCDFTests/SwiftNetCDFTests.swift +++ b/Tests/SwiftNetCDFTests/SwiftNetCDFTests.swift @@ -12,6 +12,9 @@ final class SwiftNetCDFTests: XCTestCase { let file = try NetCDF.create(path: "test.nc", overwriteExisting: true) try file.setAttribute("TITLE", "My data set") + // Write attribute as [Char] instead of string with 0 terminator + try file.setAttribute("TITLE_CHAR", Array("My data set".utf8CString), type: .char) + let dimensions = [ try file.createDimension(name: "LAT", length: 10), try file.createDimension(name: "LON", length: 5)