File tree Expand file tree Collapse file tree 4 files changed +60
-0
lines changed Expand file tree Collapse file tree 4 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ // Create types that automatically encode to JSON.
2+ 
3+ import  Foundation
4+ 
5+ struct  ScientificName :  Codable  { 
6+     var  genus :  String 
7+     var  species :  String 
8+     var  subspecies :  String ? 
9+ } 
10+ 
11+ let  momiji  =  ScientificName ( genus:  " Acer " ,  species:  " palmatum " ) 
12+ let  jsonData  =  try JSONEncoder ( ) . encode ( momiji) 
13+ 
14+ // {"genus":"Acer","species":"palmatum"}
Original file line number Diff line number Diff line change 1+ // Easily reason about data that may or may not be present.
2+ 
3+ struct  ScientificName  { 
4+     var  genus :  String 
5+     var  species :  String 
6+     var  subspecies :  String ? 
7+ 
8+     var  description :  String  { 
9+         var  text  =  " \( genus)   \( species) " 
10+         if  let  subspecies { 
11+             // subspecies is guaranteed to be non-nil here.
12+             text +=  " subsp.  \( subspecies) " 
13+         } 
14+         return  text
15+     } 
16+ } 
Original file line number Diff line number Diff line change 1+ // Use functional programming techniques.
2+ 
3+ import  Foundation
4+ 
5+ func  squareWave( phase:  Float ,  overtones:  UInt )  ->  Float  { 
6+     return  ( 0 ... overtones) 
7+         . map  { 
8+             let  harmonic  =  Float ( $0 *  2  +  1 ) 
9+             return  sinf ( phase *  harmonic)  /  harmonic
10+         } 
11+         . reduce ( 0 ,  + ) 
12+ } 
Original file line number Diff line number Diff line change 1+ // Multiline strings with string interpolation.
2+ 
3+ let  hello  =  " Hello, world! " 
4+ let  multilineString  =  """ 
5+                   @@@          
6+        @@          @@@@        
7+     @@  @@@         @@@@@      
8+      @@@@@@@@@       @@@@@     
9+        @@@@@@@@@@    @@@@@@    
10+          @@@@@@@@@@  @@@@@@    
11+            @@@@@@@@@@@@@@@@@   
12+  @           @@@@@@@@@@@@@@@   
13+  @@@@@@        @@@@@@@@@@@@@   
14+    @@@@@@@@@@@@@@@@@@@@@@@@@@  
15+      @@@@@@@@@@@@@@@@@@@@@@@@  
16+          @@@@@@@@@@@@@     @  
17+                         \( hello) 
18+ """ 
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments