Swift - Snippets: Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
Zeile 20: Zeile 20:
 
  [[Swift - get file extension]]
 
  [[Swift - get file extension]]
 
  [[Swift - Strings als Double validieren]]
 
  [[Swift - Strings als Double validieren]]
 +
 +
== Files ==
 +
=== How can I get the filename without the extension? ===
 +
 +
In Swift, you can get the file name without the extension by using the lastPathComponent property of the URL class and then removing the extension using the deletingPathExtension method. Here is an example:
 +
 +
<syntaxhighlight lang="swift">
 +
let fileURL = URL(fileURLWithPath: "/path/to/file.txt")
 +
let fileNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent
 +
print(fileNameWithoutExtension) // Output: "file"
 +
</syntaxhighlight>
 +
You can also achieve the same result using the NSString API, here's an example:
 +
 +
<syntaxhighlight lang="swift">
 +
let filePath = "/path/to/file.txt"
 +
let fileNameWithoutExtension = (filePath as NSString).deletingPathExtension
 +
print(fileNameWithoutExtension) // Output: "file"
 +
</syntaxhighlight>
  
 
== JSON in Swift ==
 
== JSON in Swift ==

Version vom 3. Februar 2023, 00:20 Uhr

Links

Swift (Programmiersprache)
https://www.swift.org/

Random / Range

Mit Random erzeugt man Zufallszahlen. Mit dem Range Operator kann man Zahlenbereiche definieren.

let score = Int.random(in: 1...10)
let rating = Int.random(in: 1..<10)
let floatNumber = Float.random(in: 1...10)
let bool = Bool.random(in: 1...10)

Time

Swift - delay code execution

Sound

Swift - Play a Sound

Gestures and Motions

Swift - Shake Motion

String Manipulation

Swift - get file extension
Swift - Strings als Double validieren

Files

How can I get the filename without the extension?

In Swift, you can get the file name without the extension by using the lastPathComponent property of the URL class and then removing the extension using the deletingPathExtension method. Here is an example:

let fileURL = URL(fileURLWithPath: "/path/to/file.txt")
let fileNameWithoutExtension = fileURL.deletingPathExtension().lastPathComponent
print(fileNameWithoutExtension) // Output: "file"

You can also achieve the same result using the NSString API, here's an example:

let filePath = "/path/to/file.txt"
let fileNameWithoutExtension = (filePath as NSString).deletingPathExtension
print(fileNameWithoutExtension) // Output: "file"

JSON in Swift

Swift & JSON

Farben

UIColor Erweiterung für Hexadezimalwerte

Extensions

Swift - View Extensions