blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 6
116
| path
stringlengths 5
872
| src_encoding
stringclasses 7
values | length_bytes
int64 10
4.68M
| score
float64 2.52
5.63
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 7
4.81M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
9a95d3448b5187cf4ab64c5b06fd914dd7d4fae0
|
Swift
|
korDmitry/Convector
|
/Convector/Volume.swift
|
UTF-8
| 895
| 3.125
| 3
|
[] |
no_license
|
//
// Volume.swift
// Convector
//
// Created by Дмитрий Коробов on 18.08.17.
// Copyright © 2017 Дмитрий Коробов. All rights reserved.
//
import Foundation
struct Volume: TypeProtocol {
var unitsImperial: [UnitProtocol] = [CubicInch(), CubicFoot()]
var unitsMetric: [UnitProtocol] = [CubicMeter()]
}
//MARK: - Imperial units
struct CubicInch: UnitProtocol {
var name: String = Units.cubicInch
var translations: Dictionary<String, Double> = [
Units.cubicMeter : 1.6387e-5
]
}
struct CubicFoot: UnitProtocol {
var name: String = Units.cubicFoot
var translations: Dictionary<String, Double> = [
Units.cubicMeter : 0.0283168
]
}
//MARK: - Metric units
struct CubicMeter: UnitProtocol {
var name: String = Units.cubicMeter
var translations: Dictionary<String, Double> = [
Units.cubicInch : 61023.7,
Units.cubicFoot : 35.3147
]
}
| true
|
9254a890077176f00624f1a010bfefc48e01063a
|
Swift
|
UsiantsevStepan/MoviesApp
|
/MoviesApp/UI/MovieDetails/Cells/MoviesBudgetAndRevenueCell.swift
|
UTF-8
| 3,032
| 2.546875
| 3
|
[] |
no_license
|
//
// MoviesBudgetAndRevenueCell.swift
// MoviesApp
//
// Created by Степан Усьянцев on 06.01.2021.
//
import UIKit
class MoviesBudgetAndRevenueCell: UITableViewCell {
static let reuseId = "MoviesBudgetAndRevenueCellReuseId"
private let movieBudgetLabel = UILabel()
private let movieRevenueLabel = UILabel()
private let numberFormatter = NumberFormatter()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.contentView.isUserInteractionEnabled = false
addSubviews()
setConstraints()
configureSubviews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func prepareForReuse() {
super.prepareForReuse()
movieBudgetLabel.text = nil
movieRevenueLabel.text = nil
}
func configure(budget: Int?, revenue: Int?) {
numberFormatter.numberStyle = .decimal
if let budget = budget, budget != 0 {
let formattedBudget = numberFormatter.string(from: NSNumber(value: budget))
movieBudgetLabel.text = "$" + (formattedBudget ?? "") + " - budget"
} else {
movieBudgetLabel.isHidden = true
}
if let revenue = revenue, revenue != 0 {
let formattedRevenue = numberFormatter.string(from: NSNumber(value: revenue))
movieRevenueLabel.text = "$" + (formattedRevenue ?? "") + " - revenue"
} else {
movieRevenueLabel.isHidden = true
}
}
private func addSubviews() {
[movieBudgetLabel, movieRevenueLabel].forEach(self.addSubview)
}
private func setConstraints() {
movieBudgetLabel.translatesAutoresizingMaskIntoConstraints = false
movieBudgetLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
movieBudgetLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
movieBudgetLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
movieRevenueLabel.translatesAutoresizingMaskIntoConstraints = false
movieRevenueLabel.topAnchor.constraint(equalTo: movieBudgetLabel.bottomAnchor, constant: 8).isActive = true
movieRevenueLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true
movieRevenueLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
movieRevenueLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16).isActive = true
}
private func configureSubviews() {
movieBudgetLabel.numberOfLines = 0
movieRevenueLabel.numberOfLines = 0
movieBudgetLabel.font = UIFont.systemFont(ofSize: 16)
movieRevenueLabel.font = UIFont.systemFont(ofSize: 16)
}
}
| true
|
abe5f3b5ddfcd714db9430500e30e19654f45f96
|
Swift
|
vincent-coetzee/ArgonWorx
|
/ArgonWorx/Symbols/Modules/ArgonModule.swift
|
UTF-8
| 25,187
| 2.6875
| 3
|
[] |
no_license
|
//
// ArgonModule.swift
// ArgonWx
//
// Created by Vincent Coetzee on 3/7/21.
//
import Foundation
///
///
/// The ArgonModule contains all the standard types and methods
/// defined by the Argon language. There is only a single instance
/// of the ArgonModule in any system running Argon, it can be accessed
/// via the accessor variable on the ArgonModule class.
///
///
public class ArgonModule: SystemModule
{
public override var typeCode:TypeCode
{
.argonModule
}
public var nilClass: Class
{
return(self.lookup(label: "Nil") as! Class)
}
public var number: Class
{
return(self.lookup(label: "Number") as! Class)
}
public var readStream: Class
{
return(self.lookup(label: "ReadStream") as! Class)
}
public var stream: Class
{
return(self.lookup(label: "Stream") as! Class)
}
public var date: Class
{
return(self.lookup(label: "Date") as! Class)
}
public var time: Class
{
return(self.lookup(label: "Time") as! Class)
}
public var byte: Class
{
return(self.lookup(label: "Byte") as! Class)
}
public var symbol: Class
{
return(self.lookup(label: "Symbol") as! Class)
}
public var void: Class
{
return(self.lookup(label: "Void") as! Class)
}
public var float: Class
{
return(self.lookup(label: "Float") as! Class)
}
public var uInteger: Class
{
return(self.lookup(label: "UInteger") as! Class)
}
public var writeStream: Class
{
return(self.lookup(label: "WriteStream") as! Class)
}
public var boolean: Class
{
return(self.lookup(label: "Boolean") as! Class)
}
public var collection: Class
{
return(self.lookup(label: "Collection") as! Class)
}
public var string: Class
{
return(self.lookup(label: "String") as! Class)
}
public var methodInstance: Class
{
return(self.lookup(label: "MethodInstance") as! Class)
}
public var `class`: Class
{
return(self.lookup(label: "Class") as! Class)
}
public var metaclass: Class
{
return(self.lookup(label: "Metaclass") as! Class)
}
public var array: ArrayClass
{
return(self.lookup(label: "Array") as! ArrayClass)
}
public var vector: ArrayClass
{
return(self.lookup(label: "Vector") as! ArrayClass)
}
public var dictionary: Class
{
return(self.lookup(label: "Dictionary") as! Class)
}
public var slot: Class
{
return(self.lookup(label: "Slot") as! Class)
}
public var parameter: Class
{
return(self.lookup(label: "Parameter") as! Class)
}
public var method: Class
{
return(self.lookup(label: "Method") as! Class)
}
public var pointer: ParameterizedSystemClass
{
return(self.lookup(label: "Pointer") as! ParameterizedSystemClass)
}
public var object: Class
{
return(self.lookup(label: "Object") as! Class)
}
public var function: Class
{
return(self.lookup(label: "Function") as! Class)
}
public var invokable: Class
{
return(self.lookup(label: "Invokable") as! Class)
}
public var list: Class
{
return(self.lookup(label: "List") as! Class)
}
public var listNode: Class
{
return(self.lookup(label: "ListNode") as! Class)
}
public var typeClass: Class
{
return(self.lookup(label: "Type") as! Class)
}
public var block: Class
{
return(self.lookup(label: "Block") as! Class)
}
public var integer: Class
{
return(self.lookup(label: "Integer") as! Class)
}
public var address: Class
{
return(self.lookup(label: "Address") as! Class)
}
public var dictionaryBucket: Class
{
return(self.lookup(label: "DictionaryBucket") as! Class)
}
public var moduleClass: Class
{
return(self.lookup(label: "Module") as! Class)
}
public var instructionArray: Class
{
return(self.lookup(label: "InstructionArray") as! Class)
}
public var enumerationCase: Class
{
return(self.lookup(label: "EnumerationCase") as! Class)
}
public var tuple: Class
{
return(self.lookup(label: "Tuple") as! Class)
}
public var dateTime: Class
{
return(self.lookup(label: "DateTime") as! Class)
}
public var module: Class
{
return(self.lookup(label: "Module") as! Class)
}
public var closure: ClosureClass
{
return(self.lookup(label: "Closure") as! ClosureClass)
}
public var enumeration: Class
{
return(self.lookup(label: "Enumeration") as! Class)
}
public var instruction: Class
{
return(self.lookup(label: "Instruction") as! Class)
}
public static let argonModule = ArgonModule(label:"Argon")
public static func configure()
{
_ = ArgonModule.argonModule
TopModule.topModule.addSymbol(ArgonModule.argonModule)
ArgonModule.argonModule.initTypes()
ArgonModule.argonModule.initBaseMethods()
ArgonModule.argonModule.initSlots()
ArgonModule.argonModule.resolveReferences()
ArgonModule.argonModule.layout()
}
private var collectionModule: SystemModule
{
return(self.lookup(label: "Collections") as! SystemModule)
}
private var streamsModule: SystemModule
{
return(self.lookup(label: "Streams") as! SystemModule)
}
private var numbersModule: SystemModule
{
return(self.lookup(label: "Numbers") as! SystemModule)
}
private func initTypes()
{
self.addSymbol(SystemClass(label:"Address").superclass("\\\\Argon\\Numbers\\UInteger"))
let collections = SystemModule(label:"Collections")
self.addSymbol(collections)
let streams = SystemModule(label:"Streams")
self.addSymbol(streams)
let numbers = SystemModule(label:"Numbers")
self.addSymbol(numbers)
collections.addSymbol(ArrayClass(label:"Array",superclasses:["\\\\Argon\\Collections\\Collection","\\\\Argon\\Collections\\Iterable"],parameters:["INDEX","ELEMENT"]).slotClass(ArraySlot.self).mcode("a"))
collections.addSymbol(ArrayClass(label:"ByteArray",superclasses:["\\\\Argon\\Collections\\Array","\\\\Argon\\Collections\\Iterable"],parameters:["INDEX"]).slotClass(ArraySlot.self))
collections.addSymbol(ArrayClass(label:"InstructionArray",superclasses:["\\\\Argon\\Collections\\Array","\\\\Argon\\Collections\\Iterable"],parameters:["INDEX","Instruction"]).slotClass(ArraySlot.self))
self.addSymbol(SystemClass(label:"Behavior").superclass("\\\\Argon\\Object"))
self.addSymbol(SystemClass(label:"Block").superclass("\\\\Argon\\Object"))
self.addSymbol(PrimitiveClass.byteClass.superclass("\\\\Argon\\Magnitude").mcode("b"))
self.addSymbol(PrimitiveClass.booleanClass.superclass("\\\\Argon\\Object").slotClass(BooleanSlot.self).mcode("l"))
self.addSymbol(PrimitiveClass.characterClass.superclass("\\\\Argon\\Magnitude").mcode("c"))
self.addSymbol(SystemClass(label:"Class").superclass("\\\\Argon\\Type").slotClass(ObjectSlot.self).mcode("s"))
self.addSymbol(ClosureClass(label:"Closure").superclass("\\\\Argon\\Function").slotClass(ObjectSlot.self))
collections.addSymbol(SystemClass(label:"Collection").superclass("\\\\Argon\\Object").superclass("\\\\Argon\\Collections\\Iterable"))
self.addSymbol(PrimitiveClass.dateClass.superclass("\\\\Argon\\Magnitude"))
self.addSymbol(PrimitiveClass.dateTimeClass.superclass("\\\\Argon\\Date").superclass("\\\\Argon\\Time"))
collections.addSymbol(ParameterizedSystemClass(label:"Dictionary",superclasses:["\\\\Argon\\Collections\\Collection","\\\\Argon\\Collections\\Iterable"],parameters:["KEY","VALUE"]).mcode("d"))
collections.addSymbol(SystemClass(label:"DictionaryBucket").superclass("\\\\Argon\\Object"))
self.addSymbol(SystemClass(label:"Enumeration").superclass("\\\\Argon\\Type").mcode("e"))
self.addSymbol(SystemClass(label:"EnumerationCase").superclass("\\\\Argon\\Object").mcode("u"))
self.addSymbol(SystemClass(label:"Error").superclass("\\\\Argon\\Object"))
self.addSymbol(SystemClass(label:"Expression").superclass("\\\\Argon\\Object"))
numbers.addSymbol(TaggedPrimitiveClass.floatClass.superclass("\\\\Argon\\Numbers\\Number"))
self.addSymbol(SystemClass(label:"Function").superclass("\\\\Argon\\Invokable").mcode("f"))
numbers.addSymbol(TaggedPrimitiveClass.integerClass.superclass("\\\\Argon\\Numbers\\Number").slotClass(IntegerSlot.self).mcode("i"))
self.addSymbol(SystemClass(label:"Invokable").superclass("\\\\Argon\\Behavior"))
self.addSymbol(SystemClass(label:"Instruction").superclass("\\\\Argon\\Object"))
collections.addSymbol(ParameterizedSystemClass(label:"Iterable",superclasses:["\\\\Argon\\Object"],parameters:["ELEMENT"]))
collections.addSymbol(ParameterizedSystemClass(label:"List",superclasses:["\\\\Argon\\Collections\\Collection","\\\\Argon\\Collections\\Iterable"],parameters:["ELEMENT"]))
collections.addSymbol(ParameterizedSystemClass(label:"ListNode",superclasses:["\\\\Argon\\Collections\\Collection"],parameters:["ELEMENT"]))
self.addSymbol(SystemClass(label:"Magnitude").superclass("\\\\Argon\\Object"))
self.addSymbol(SystemClass(label:"Metaclass",typeCode:.metaclass).superclass("\\\\Argon\\Class").mcode("g"))
self.addSymbol(SystemClass(label:"Method",typeCode:.method).superclass("\\\\Argon\\Invokable").mcode("m"))
self.addSymbol(SystemClass(label:"MethodInstance",typeCode:.methodInstance).superclass("\\\\Argon\\Invokable").mcode("h"))
self.addSymbol(SystemClass(label:"Module",typeCode:.module).superclass("\\\\Argon\\Type"))
self.addSymbol(PrimitiveClass.mutableStringClass.superclass("\\\\Argon\\String").mcode("t"))
self.addSymbol(SystemClass(label:"Nil").superclass("\\\\Argon\\Object").mcode("j"))
numbers.addSymbol(SystemClass(label:"Number").superclass("\\\\Argon\\Magnitude"))
self.addSymbol(SystemClass(label:"Object").mcode("k"))
self.addSymbol(SystemClass(label:"Parameter").superclass("\\\\Argon\\Slot"))
self.addSymbol(ParameterizedSystemClass(label:"Pointer",superclasses:["\\\\Argon\\Object"],parameters:["ELEMENT"],typeCode:.pointer).mcode("r"))
streams.addSymbol(SystemClass(label:"ReadStream",typeCode:.stream).superclass("\\\\Argon\\Streams\\Stream"))
streams.addSymbol(SystemClass(label:"ReadWriteStream",typeCode:.stream).superclass("\\\\Argon\\Streams\\ReadStream").superclass("\\\\Argon\\Streams\\WriteStream"))
collections.addSymbol(ParameterizedSystemClass(label:"Set",superclasses:["\\\\Argon\\Collections\\Collection","\\\\Argon\\Collections\\Iterable"],parameters:["ELEMENT"]))
self.addSymbol(SystemClass(label:"Slot",typeCode:.slot).superclass("\\\\Argon\\Object").mcode("p"))
streams.addSymbol(SystemClass(label:"Stream",typeCode:.stream).superclass("\\\\Argon\\Object"))
self.addSymbol(PrimitiveClass.stringClass.superclass("\\\\Argon\\Object").slotClass(StringSlot.self).mcode("q"))
self.addSymbol(SystemClass(label:"Symbol",typeCode:.symbol).superclass("\\\\Argon\\String").mcode("n"))
self.addSymbol(PrimitiveClass.timeClass.superclass("\\\\Argon\\Magnitude"))
self.addSymbol(SystemClass(label:"Tuple",typeCode:.tuple).superclass("\\\\Argon\\Type").mcode("v"))
self.addSymbol(SystemClass(label:"Type",typeCode:.type).superclass("\\\\Argon\\Object"))
numbers.addSymbol(TaggedPrimitiveClass.uIntegerClass.superclass("\\\\Argon\\Numbers\\Number").mcode("x"))
collections.addSymbol(ArrayClass(label:"Vector",superclasses:["\\\\Argon\\Collections\\Collection","\\\\Argon\\Collections\\Iterable"],parameters:["INDEX","ELEMENT"]).slotClass(ArraySlot.self).mcode("y"))
self.addSymbol(VoidClass.voidClass.superclass("\\\\Argon\\Object").mcode("z"))
streams.addSymbol(SystemClass(label:"WriteStream",typeCode:.stream).superclass("\\\\Argon\\Streams\\Stream"))
}
private func initSlots()
{
self.object.slot("hash",self.integer)
self.array.hasBytes(true)
self.block.slot("count",self.integer).slot("blockSize",self.integer).slot("nextBlock",self.address)
self.class.slot("superclasses",self.array.of(self.class)).virtual("subclasses",self.array.of(self.class)).slot("slots",self.array.of(self.slot)).slot("extraSizeInBytes",self.integer).slot("instanceSizeInBytes",self.integer).slot("hasBytes",self.boolean).slot("isValue",self.boolean).slot("magicNumber",self.integer)
self.closure.slot("codeSegment",self.address).slot("initialIP",self.address).slot("localCount",self.integer).slot("localSlots",self.array.of(self.slot)).slot("contextPointer",self.address).slot("instructions",self.array.of(self.instruction)).slot("parameters",self.array.of(self.parameter)).slot("returnType",self.typeClass)
self.collection.slot("count",self.integer).slot("size",self.integer).slot("elementType",self.typeClass)
self.date.virtual("day",self.integer).virtual("month",self.string).virtual("monthIndex",self.integer).virtual("year",self.integer)
self.dateTime.virtual("date",self.date).virtual("time",self.time)
self.dictionary.slot("hashFunction",self.closure).slot("prime",self.integer)
self.dictionaryBucket.slot("key",self.object).slot("value",self.object).slot("next",self.dictionaryBucket)
self.enumeration.slot("rawType",self.typeClass).slot("cases",self.array.of(self.enumerationCase))
self.enumerationCase.slot("symbol",self.symbol).slot("associatedTypes",self.array.of(self.typeClass)).slot("enumeration",self.enumeration).slot("rawType",self.integer).slot("caseSizeInBytes",self.integer).slot("index",self.integer)
self.function.slot("name",self.string).slot("parameters",self.array.of(self.parameter)).slot("resultType",self.typeClass).slot("code",self.instructionArray).slot("localSlots",self.array.of(self.slot)).slot("libraryPath",self.string).slot("libraryHandle",self.address).slot("librarySymbol",self.address)
self.instruction.virtual("opcode",self.integer).virtual("mode",self.integer).virtual("operand1",self.integer).virtual("operand2",self.integer).virtual("operand3",self.integer)
self.instructionArray.hasBytes(true)
self.list.slot("elementSize",self.integer).slot("first",self.listNode).slot("last",self.listNode)
self.listNode.slot("element",self.object).slot("next",self.listNode).slot("previous",self.listNode)
self.method.slot("instances",self.array.of(self.methodInstance))
self.methodInstance.slot("name",self.string).slot("parameters",self.array.of(self.parameter)).slot("resultType",self.typeClass).slot("code",self.instructionArray).slot("localSlots",self.array.of(self.slot))
self.moduleClass.virtual("isSystemModule",self.boolean).slot("elements",self.typeClass).slot("isArgonModule",self.boolean).slot("isTopModule",self.boolean).slot("slots",self.array.of(self.slot)).slot("instanceSizeInBytes",self.integer)
self.slot.slot("name",self.string).slot("type",self.typeClass).slot("offset",self.integer).slot("typeCode",self.integer)
self.stream.slot("fileHandle",self.integer).slot("count",self.integer).virtual("isOpen",self.boolean).virtual("canRead",self.boolean).virtual("canWrite",self.boolean)
self.string.slot("count",self.integer).virtual("bytes",self.address).hasBytes(true)
self.time.virtual("hour",self.integer).virtual("minute",self.integer).virtual("second",self.integer).virtual("millisecond",self.integer)
self.tuple.slot("slots",self.array.of(self.slot)).slot("instanceSizeInBytes",self.integer)
self.typeClass.slot("name",self.string).slot("typeCode",self.integer)
self.vector.slot("startBlock",self.block).slot("blockCount",self.integer).hasBytes(true)
}
private func initBaseMethods()
{
let numbersModule = self.numbersModule
numbersModule.addSymbol(IntrinsicMethodInstance(left:"TYPE","+",right:"TYPE",out:"TYPE").where("TYPE",self.number).method)
numbersModule.addSymbol(IntrinsicMethodInstance(left:"TYPE","-",right:"TYPE",out:"TYPE").where("TYPE",self.number).method)
numbersModule.addSymbol(IntrinsicMethodInstance(left:"TYPE","*",right:"TYPE",out:"TYPE").where("TYPE",self.number).method)
numbersModule.addSymbol(IntrinsicMethodInstance(left:"TYPE","/",right:"TYPE",out:"TYPE").where("TYPE",self.number).method)
numbersModule.addSymbol(IntrinsicMethodInstance(left:"TYPE","%",right:"TYPE",out:"TYPE").where("TYPE",self.number).method)
numbersModule.addSymbol(LibraryMethodInstance(left:self.float,"truncate",right:self.float,out:self.integer).method)
numbersModule.addSymbol(LibraryMethodInstance(left:self.float,"ceiling",right:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance(left:self.float,"floor",right:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance(left:self.float,"round",right:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("sin",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("cos",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("tan",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("asin",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("acos",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("atan",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("ln",arg:self.float,out:self.float).method)
numbersModule.addSymbol(LibraryMethodInstance("exp",arg:self.float,out:self.float).method)
let streams = self.streamsModule
streams.addSymbol(LibraryMethodInstance("next",self.readStream,"TYPE",self.integer).where("TYPE",self.object).method)
streams.addSymbol(LibraryMethodInstance("nextPut",self.writeStream,"TYPE",self.integer).where("TYPE",self.object).method)
streams.addSymbol(LibraryMethodInstance("open",self.string,self.string,"TYPE").where("TYPE",self.readStream).where("TYPE",self.writeStream).method)
streams.addSymbol(LibraryMethodInstance("close",self.stream,self.boolean).method)
streams.addSymbol(LibraryMethodInstance("tell",self.stream,self.integer).method)
streams.addSymbol(LibraryMethodInstance("flush",self.stream,self.boolean).method)
streams.addSymbol(LibraryMethodInstance("seek",self.stream,self.integer,self.boolean).method)
streams.addSymbol(LibraryMethodInstance("nextLine",self.stream,self.string,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextPutLine",self.stream,self.string,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextByte",self.stream,self.byte,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextPutByte",self.stream,self.byte,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextFloat",self.stream,self.float).method)
streams.addSymbol(LibraryMethodInstance("nextPutFloat",self.stream,self.float,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextInteger",self.stream,self.integer).method)
streams.addSymbol(LibraryMethodInstance("nextPutInteger",self.stream,self.integer,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextString",self.stream,self.string).method)
streams.addSymbol(LibraryMethodInstance("nextPutString",self.stream,self.string,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextSymbol",self.stream,self.symbol).method)
streams.addSymbol(LibraryMethodInstance("nextPutSymbol",self.stream,self.symbol,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextUInteger",self.stream,self.uInteger).method)
streams.addSymbol(LibraryMethodInstance("nextPutUInteger",self.stream,self.uInteger,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextDate",self.stream,self.date).method)
streams.addSymbol(LibraryMethodInstance("nextPutDate",self.stream,self.date,self.void).method)
streams.addSymbol(LibraryMethodInstance("nextTime",self.stream,self.time).method)
streams.addSymbol(LibraryMethodInstance("nextPutTime",self.stream,self.time,self.void).method)
let collections = self.collectionModule
collections.addSymbol(LibraryMethodInstance("at",self.array,self.integer,"TYPE").method)
collections.addSymbol(LibraryMethodInstance("atPut",self.array,self.integer,"TYPE",self.void).method)
collections.addSymbol(LibraryMethodInstance("atPutAll",self.array,self.integer,self.array,self.void).method)
collections.addSymbol(LibraryMethodInstance("contains",self.array,"TYPE",self.boolean).method)
collections.addSymbol(LibraryMethodInstance("containsAll",self.array,self.array,self.boolean).method)
collections.addSymbol(LibraryMethodInstance("last",self.array,"TYPE").method)
collections.addSymbol(LibraryMethodInstance("first",self.array,"TYPE").method)
collections.addSymbol(LibraryMethodInstance("add",self.array,"TYPE").method)
collections.addSymbol(LibraryMethodInstance("addAll",self.array,self.array).method)
collections.addSymbol(LibraryMethodInstance("removeAt",self.array,self.integer).method)
collections.addSymbol(LibraryMethodInstance("removeAll",self.array,self.array).method)
collections.addSymbol(LibraryMethodInstance("withoutFirst",self.array,self.array).method)
collections.addSymbol(LibraryMethodInstance("withoutLast",self.array,self.array).method)
collections.addSymbol(LibraryMethodInstance("withoutFirst",self.array,self.integer,self.array).method)
collections.addSymbol(LibraryMethodInstance("withoutLast",self.array,self.integer,self.array).method)
let strings = SymbolGroup(label:"String Methods")
self.addSymbol(strings)
strings.addSymbol(LibraryMethodInstance("separatedBy",self.string,self.string,self.array.of(self.string)).method)
strings.addSymbol(LibraryMethodInstance("joinedWith",self.array.of(self.string),self.string,self.string).method)
strings.addSymbol(LibraryMethodInstance("contains",self.string,self.string,self.boolean).method)
strings.addSymbol(LibraryMethodInstance("hasPrefix",self.string,self.string,self.boolean).method)
strings.addSymbol(LibraryMethodInstance("hasSuffix",self.string,self.string,self.boolean).method)
strings.addSymbol(LibraryMethodInstance("prefixedWith",self.string,self.string,self.string).method)
strings.addSymbol(LibraryMethodInstance("suffixedWith",self.string,self.string,self.boolean).method)
}
///
///
/// We need a special layout algorithm because this module has
/// complex dependencies.
///
///
internal override func layout()
{
print("LAYING OUT SLOTS")
self.layoutSlots()
for aClass in self.classes.sorted(by: {$0.name<$1.name})
{
aClass.printLayout()
}
print("LAID OUT SLOTS")
///
///
/// Now do layouts in a specific order
///
print("LAYING OUT MEMORY")
let segment = ManagedSegment.shared
let classes = self.classes
for aClass in classes
{
aClass.preallocateMemory(size: InnerPointer.kClassSizeInBytes,in: segment)
}
for aClass in classes
{
aClass.layoutInMemory(segment: ManagedSegment.shared)
}
for instance in self.methodInstances
{
instance.layoutInMemory(segment: ManagedSegment.shared)
}
print("LAID OUT MEMORY")
}
}
| true
|
5d5444299bb1699655c5c96c0509d706bb598f65
|
Swift
|
pbajwa8/CourseChat
|
/CourseChat/ViewController.swift
|
UTF-8
| 1,421
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// CourseChat
//
// Created by Parambir Bajwa on 5/9/15.
// Copyright (c) 2015 Parambir Bajwa. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var classField: UITextField!
@IBOutlet var contentField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
classField.becomeFirstResponder()
navigationController?.navigationBarHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButton(sender: AnyObject) {
self.performSegueWithIdentifier("cancel", sender: self)
}
@IBAction func submitButton(sender: AnyObject) {
var user = PFUser.currentUser()
// Make a new post
var post = PFObject(className:"Post")
post["title"] = classField.text
post["body"] = contentField.text
post["user"] = user
post.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
println("we made it")
self.performSegueWithIdentifier("success", sender: self)
} else {
println("failure")
}
}
}
}
| true
|
090c6a6ce651f22f4869e1c59b25ad6c3f88221f
|
Swift
|
zyvv/Radioio
|
/watchOS Extension/WatchMainView.swift
|
UTF-8
| 2,516
| 2.828125
| 3
|
[] |
no_license
|
//
// WatchMainView.swift
// Radioio WatchKit Extension
//
// Created by 张洋威 on 2021/2/22.
//
import SwiftUI
struct WatchMainView: View {
@EnvironmentObject var playerControl: PlayerControl
@EnvironmentObject var radioViewModel: RadioViewModel
@State var isPlaying: Bool = false
@State var favourite = false
var body: some View {
VStack {
Spacer()
VStack(alignment: .leading, spacing: 2) {
HStack(alignment: .firstTextBaseline) {
PlayingStatusView(playingStatus: Binding.constant(playerControl.playerStatus))
.frame(width: 12, height: 12)
Text(playerControl.playingRadio.name)
.font(.title3)
.bold()
.multilineTextAlignment(.center)
}
if playerControl.playingRadio.desc != nil {
Text(playerControl.playingRadio.desc!)
.font(.caption)
.padding(.leading, 16)
}
}
Spacer()
HStack {
Spacer()
Button(action: {
playerControl.toggle()
}) {
Image(systemName: (isPlaying ? "pause.circle" : "play.circle"))
.font(.system(size: 45))
.foregroundColor(.white)
}
.buttonStyle(PlainButtonStyle())
Spacer()
Button(action: {
favourite = playerControl.favouriteRadio(radio: playerControl.playingRadio)
radioViewModel.shouldFetchFavouriteRadio.send(true)
}) {
Image(systemName: (favourite ? "heart.fill" : "heart"))
.font(.system(size: 25))
.foregroundColor(.white)
}
.buttonStyle(PlainButtonStyle())
Spacer()
}
Spacer()
}
.onReceive(playerControl.$playingRadio) {
favourite = $0.favourite
}
.onReceive(playerControl.$playerStatus) {
isPlaying = $0 != .pause
if $0 == .playing {
radioViewModel.shouldFetchRecentPlayRadio.send(true)
}
}
}
}
struct WatchMainView_Previews: PreviewProvider {
static var previews: some View {
WatchMainView()
}
}
| true
|
308ea1d6a4a4d67e1879cc1c27cbb34baccbd7f5
|
Swift
|
Liggidarck/Comject-iOS
|
/ProjectDevil/MainViews/Explore/ExploreView.swift
|
UTF-8
| 5,154
| 2.796875
| 3
|
[] |
no_license
|
//
// ExploreView.swift
// ProjectDevil
//
// Created by George Filatov on 13.01.2021.
//
import SwiftUI
struct ExploreView: View {
var body: some View {
NavigationView{
ScrollView {
NavigationLink(
destination: ProjectOtherUser(),
label: {
ExplorePost().padding()
})
NavigationLink(
destination: ProjectOtherUser(),
label: {
ExplorePost().padding()
})
}
.navigationTitle("Explore")
.navigationBarItems(trailing:
NavigationLink( destination: FiltersView(),
label: {
Image(systemName: "personalhotspot").imageScale(.large)
}
)
)
}
}
}
struct ExplorePost: View {
var body: some View {
VStack {
HStack {
NavigationLink(
destination: ProfileView(),
label: {
AvaViewKate()
.frame(width: 45, height: 75, alignment: .center)
.padding(.horizontal, -20)
.padding(.top, -20)
.padding(.bottom, -30)
.padding()
})
VStack(alignment: .leading) {
Text("Kate Sheptukhina")
.foregroundColor(.primary)
Text("@kate_sheee")
.font(.caption2)
.foregroundColor(.secondary)
}.padding(.top, 10)
Spacer()
} .padding(.leading)
Image("2")
.resizable()
.aspectRatio(16/9, contentMode: .fit)
HStack {
VStack(alignment: .leading) {
Text("Title goes here")
.font(.title)
.foregroundColor(.primary)
Text("Long default text for you project. Long continuation of the description. Мой уровень английского не позволяет сделать мне более длинный текст на английском, поэтому продолжу на русском чтобы текст описания выглядил более объёмно.")
.font(.caption)
.foregroundColor(.secondary)
.padding(.top, 10.0)
Text("#Информатика #Программирование #IT")
.font(.caption)
.foregroundColor(.blue)
.padding(.top, 3.0)
}.layoutPriority(100)
Spacer()
}.padding()
likes_and_comment().padding(.leading)
buttons_posts_explore().padding()
}
.cornerRadius(10)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(Color(.sRGB, red:150/255, green: 150/255, blue: 150/255, opacity: 0.2), lineWidth: 1))
}
}
struct buttons_posts_explore: View {
var body: some View{
HStack {
Button(action: {
}) {
HStack(spacing: -10.0) {
Image(systemName: "heart")
.foregroundColor(.secondary)
.padding(5)
.padding(.leading, 5)
Text("LIKE")
.padding(.horizontal, 30.0)
.padding(.vertical, 10.0)
.font(.system(size: 14))
.foregroundColor(.secondary)
}
}.overlay(RoundedRectangle(cornerRadius: 3)
.stroke(Color.gray, lineWidth: 0.5))
Spacer()
NavigationLink(
destination: CommentsView(),
label: {
HStack(spacing: -10.0) {
Image(systemName: "message")
.foregroundColor(.secondary)
.padding(5)
.padding(.leading, 5)
Text("COMMENT")
.padding(.horizontal, 30.0)
.padding(.vertical, 10.0)
.font(.system(size: 14))
.foregroundColor(.secondary)
}.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.gray, lineWidth: 0.5))
})
}
}
}
struct ExploreView_Previews: PreviewProvider {
static var previews: some View {
ExploreView()
ExplorePost()
}
}
| true
|
6369ce10fa82bf9466bce94b4bbd6852f356a33f
|
Swift
|
Charleo85/WuChat
|
/TSWeChat/Classes/Chat/Views/TSChatVoiceIndicatorView.swift
|
UTF-8
| 3,680
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// TSRecordIndicatorView.swift
// TSWeChat
//
// Created by Hilen on 12/22/15.
// Copyright © 2015 Hilen. All rights reserved.
//
import UIKit
class TSChatVoiceIndicatorView: UIView {
@IBOutlet weak var centerView: UIView!{didSet { //中央的灰色背景 view
centerView.layer.cornerRadius = 4.0
centerView.layer.masksToBounds = true
}}
@IBOutlet weak var noteLabel: UILabel! {didSet { //提示的 label
noteLabel.layer.cornerRadius = 2.0
noteLabel.layer.masksToBounds = true
}}
@IBOutlet weak var cancelImageView: UIImageView! //取消提示
@IBOutlet weak var signalValueImageView: UIImageView! //音量的图片
@IBOutlet weak var recordingView: UIView! //录音整体的 view,控制是否隐藏
@IBOutlet weak var tooShotPromptImageView: UIImageView! //录音时间太短的提示
override init (frame : CGRect) {
super.init(frame : frame)
self.initContent()
}
convenience init () {
self.init(frame:CGRect.zero)
self.initContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initContent() {
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
//对外交互的 view 控制
// MARK: - @extension TSChatVoiceIndicatorView
extension TSChatVoiceIndicatorView {
//正在录音
func recording() {
self.hidden = false
self.cancelImageView.hidden = true
self.tooShotPromptImageView.hidden = true
self.recordingView.hidden = false
self.noteLabel.backgroundColor = UIColor.clearColor()
self.noteLabel.text = "手指上滑,取消发送"
}
//录音过程中音量的变化
func signalValueChanged(value: CGFloat) {
}
//滑动取消
func slideToCancelRecord() {
self.hidden = false
self.cancelImageView.hidden = false
self.tooShotPromptImageView.hidden = true
self.recordingView.hidden = true
self.noteLabel.backgroundColor = UIColor(rgba: "#9C3638")
self.noteLabel.text = "松开手指,取消发送"
}
//录音时间太短的提示
func messageTooShort() {
self.hidden = false
self.cancelImageView.hidden = true
self.tooShotPromptImageView.hidden = false
self.recordingView.hidden = true
self.noteLabel.backgroundColor = UIColor.clearColor()
self.noteLabel.text = "说话时间太短"
//0.5秒后消失
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.endRecord()
}
}
//录音结束
func endRecord() {
self.hidden = true
}
//更新麦克风的音量大小
func updateMetersValue(value: Float) {
var index = Int(round(value))
index = index > 7 ? 7 : index
index = index < 0 ? 0 : index
let array = [
TSAsset.RecordingSignal001.image,
TSAsset.RecordingSignal002.image,
TSAsset.RecordingSignal003.image,
TSAsset.RecordingSignal004.image,
TSAsset.RecordingSignal005.image,
TSAsset.RecordingSignal006.image,
TSAsset.RecordingSignal007.image,
TSAsset.RecordingSignal008.image,
]
self.signalValueImageView.image = array.get(index)
}
}
| true
|
23ea96fb83d577f63c8b132ffeff1028d7039207
|
Swift
|
DonMag/SWEmbeddedPageView
|
/SWEmbeddedPageView/SWEmbeddedPageView/BaseWithContainerViewController.swift
|
UTF-8
| 3,307
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// BaseWithContainerViewController.swift
// SWEmbeddedPageView
//
// Created by Don Mini on 7/8/17.
// Copyright © 2017 DonMag. All rights reserved.
//
import UIKit
// MARK: "Base" View Controller - has a Container View which holds a Page View Controller
class BaseWithContainerViewController: UIViewController {
}
// MARK: View Controller to use as our "page" (see storyboard)
class MyPageVC: UIViewController {
}
// MARK: Our UIPageViewController class
class MyPageViewController: UIPageViewController {
private(set) lazy var thePageVCs: [UIViewController] = {
return [
self.newPageVC(UIColor.red),
self.newPageVC(UIColor.green),
self.newPageVC(UIColor.blue),
self.newPageVC(UIColor.orange),
self.newPageVC(UIColor.magenta),
self.newPageVC(UIColor.cyan),
self.newPageVC(UIColor.purple),
]
}()
private func newPageVC(_ color: UIColor) -> UIViewController {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "myPageVC") ?? UIViewController()
vc.view.backgroundColor = color
// uncomment for simple rounded corners on the "pages"
vc.view.clipsToBounds = true
vc.view.layer.cornerRadius = 20.0
return vc
}
// setup our page controller - Scroll, Horizontal, 20-pts spacing... this will override IB settings
required init?(coder aDecoder: NSCoder) {
let optionsDict = [UIPageViewControllerOptionInterPageSpacingKey : 20]
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: optionsDict)
}
override func viewDidLoad() {
super.viewDidLoad()
// see extension below
dataSource = self
// init with first page
if let firstVC = thePageVCs.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
}
}
}
// MARK: UIPageViewControllerDataSource
extension MyPageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let currIndex = thePageVCs.index(of: viewController) else {
return nil
}
let prevIndex = currIndex - 1
// Allow "looping" when swiping right on first page
guard prevIndex >= 0 else {
return thePageVCs.last
}
return thePageVCs[prevIndex]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let currIndex = thePageVCs.index(of: viewController) else {
return nil
}
let nextIndex = currIndex + 1
// Allow "looping" when swiping left on the last page
guard thePageVCs.count > nextIndex else {
return thePageVCs.first
}
return thePageVCs[nextIndex]
}
}
// MARK: UIPageViewControllerDelegate
// uncomment this block to use the built-in UIPageControl (the "dots")
/*
extension MyPageViewController: UIPageViewControllerDelegate {
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return thePageVCs.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstVC = viewControllers?.first,
let firstVCIndex = thePageVCs.index(of: firstVC) else {
return 0
}
return firstVCIndex
}
}
*/
| true
|
21fce85d0e69c4678f5d9f179d51bade186771e7
|
Swift
|
ksermione/shopify-challenge
|
/Shopify Challenge/Shopify Challenge/Domain/Models/BoardModel.swift
|
UTF-8
| 2,161
| 3.578125
| 4
|
[] |
no_license
|
//
// BoardModel.swift
// Shopify Challenge
//
// Created by Oksana Shcherban on 10.05.19.
// Copyright © 2019 Oksana Shcherban. All rights reserved.
//
import Foundation
struct BoardModel {
var letters: [[Character?]]
var boardSize: Int
init(letters: [[Character?]], boardSize: Int) {
self.letters = letters
self.boardSize = boardSize
}
}
extension BoardModel {
static func create(withWords words: [String], boardSize: Int) -> BoardModel {
// empty board
var letters = [[Character?]]()
for _ in 0...(boardSize - 1) {
var strRow = [Character?]()
for _ in 0...(boardSize - 1) {
strRow.append(nil)
}
letters.append(strRow)
}
words.forEach({ w in
if w.count <= boardSize {
let word = w.uppercased()
let maxStart = (boardSize - word.count)
var positionX = maxStart > 0 ? Int.random(in: 0..<(maxStart)) : 0
var positionY = Int.random(in: 0..<(boardSize))
while !canPlaceHorizontally(word: word, positionX: positionX, positionY: positionY, letters: letters) {
positionX = maxStart > 0 ? Int.random(in: 0..<(maxStart)) : 0
positionY = Int.random(in: 0..<(boardSize))
}
// place horizontally
word.forEach({ char in
letters[positionY][positionX] = char
positionX += 1
})
}
})
return BoardModel(letters: letters, boardSize: boardSize)
}
static private func canPlaceHorizontally(word: String, positionX: Int, positionY: Int, letters: [[Character?]]) -> Bool {
var posX = positionX
var canPlace = true
word.forEach({ char in
if (letters[positionY][posX] != nil) {
if (letters[positionY][posX] != char) {
canPlace = false
return
}
}
posX += 1
})
return canPlace
}
}
enum Direction {
case down
case right
}
| true
|
bfd6e1484d2a4e4ec8ad696d25fe94b8e8f030fd
|
Swift
|
OscarNguyen/Playground
|
/lyricsOfTheSong99BottlesOfBeer.playground/Contents.swift
|
UTF-8
| 1,094
| 3.671875
| 4
|
[] |
no_license
|
import UIKit
//let beerQuantity = [1,2,3,4,5]
//var i = 99
var result = ""
func beer() -> String{
for i in 1...99 {
result += " \(100-i) bottles of beer on the wall, \(100-i) bottles of beer.\nTake one down and pass it around, \(100-i-1) bottles of beer on the wall\n "
}
result += "\nNo more bottles of beer on the wall. Go to the store and buy some more, 99 bottles of beer on the wall"
return result
}
//print(beer())
func beer1( _ b: Int)->String{
for i in (1...b).reversed(){
if i == 1{
result += "\(i) bottle of beer on the wall, \(i) bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall\n "
}
else{
result += " \(i) bottles of beer on the wall, \(i) bottles of beer.\nTake one down and pass it around, \(i-1) bottles of beer on the wall\n "
}
}
result += "\nNo more bottles of beer on the wall. Go to the store and buy some more, 99 bottles of beer on the wall"
return result
}
print(beer1( 99))
| true
|
285c248e98f4bc88067f258e084c411ed8e9cb3e
|
Swift
|
chocomegane/ios_swift2
|
/jour/ViewController.swift
|
UTF-8
| 1,523
| 2.796875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// jour
//
// Created by yuki.sawamura on 2019/08/11.
// Copyright © 2019年 yusawamu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// 計算機の処理 start
// 数値が入る
@IBOutlet weak var filedA: UITextField!
// 数値が入る
@IBOutlet weak var filedB: UITextField!
// 結果が入る
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func celende(_ sender: Any) {
let resultA:Int? = Int(filedA.text!);
let resultB:Int? = Int(filedB.text!);
if(resultA != nil && resultB != nil ){
resultLabel.text = "答えは"+String(resultA!*resultB!);
}else{
resultLabel.text = "入力内容を再度ご確認ください"
}
}
// 計算機の処理 end
// 配列処理 staet
// 戻るボタンと紐付け用としたが失敗
@IBAction func `return`(_ sender: Any) {
// 同じコントローラの場合下記のものを使用してもろモーダルを閉じることはできない
// dismiss(animated: true, completion: nil)
}
}
| true
|
d1ca2d627cb04afd6e440f515ef99f213c951702
|
Swift
|
chrislonge/CoreML-Vision
|
/VisionMLStarter/ViewController.swift
|
UTF-8
| 4,473
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// VisionMLStarter
//
// Created by Longe, Chris on 8/13/17.
// Copyright © 2017 Longe, Chris. All rights reserved.
//
import UIKit
// Import Core ML and Vision frameworks
import CoreML
import Vision
class ViewController: UIViewController {
// MARK: - IBOutlets
// Step 1. Connect Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var selectImageButton: UIButton!
@IBOutlet weak var modelSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Step 5. Grab CIImage from UIImageView and run the detect object or scene function.
guard
let image = imageView.image,
let ciImage = CIImage(image: image) else {
fatalError("Couldn't convert UIImage to CIImage")
}
detectScene(image: ciImage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
// Step 2. Create Image Picker Action
@IBAction func selectImageTouched(_ sender: UIButton) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = .savedPhotosAlbum
present(pickerController, animated: true)
}
// Step 6. Add Segemented Control Action
@IBAction func indexChanged(_ sender: UISegmentedControl) {
guard
let image = imageView.image,
let ciImage = CIImage(image: image) else {
fatalError("Couldn't convert UIImage to CIImage")
}
detectScene(image: ciImage)
}
}
// Leave this protocol blank. It is required for the UIImagePickerController
extension ViewController: UINavigationControllerDelegate {
}
// Step 3. Implement UIImagePickerControllerDelegate in an Extension
extension ViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("couldn't load image from Photos")
}
imageView.image = image
guard let ciImage = CIImage(image: image) else {
fatalError("Couldn't convert UIImage to CIImage")
}
dismiss(animated: true)
// TODO: Call function to detect object or scenen in image.
detectScene(image: ciImage)
}
}
// Step 4. Write function that detects the dominant objects or the scene of an image in an extension.
extension ViewController {
func detectScene(image: CIImage) {
resultLabel.text = "Detecting scene..."
// A: Create a Core ML Model based on segmented control
var mlModel: VNCoreMLModel!
if modelSegmentedControl.selectedSegmentIndex == 0 {
guard let model = try? VNCoreMLModel(for: GoogLeNetPlaces().model) else {
fatalError("Couldn't load GoogLeNetPlaces ML model")
}
mlModel = model
} else {
guard let model = try? VNCoreMLModel(for: Resnet50().model) else {
fatalError("Couldn't load Resnet50 ML model")
}
mlModel = model
}
// B: Create a Vision request
let request = VNCoreMLRequest(model: mlModel) { request, error in
guard
let results = request.results as? [VNClassificationObservation],
let topResult = results.first else {
fatalError("Unexpected result type from VNCoreMLRequest")
}
DispatchQueue.main.async {
self.resultLabel.text = "\(topResult.identifier). Confidence: \(Int(topResult.confidence * 100))%"
}
}
// C: Create and Run a request handler
let handler = VNImageRequestHandler(ciImage: image)
DispatchQueue.global(qos: .userInteractive).async {
do {
try handler.perform([request])
} catch {
print(error)
}
}
}
}
| true
|
56ccad47d4f70b508d4c003fa96b2df5cbbea933
|
Swift
|
rwbutler/TailorSwift
|
/Example/TailorSwift/ViewController.swift
|
UTF-8
| 1,174
| 3.109375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// ViewController.swift
// TailorSwift
//
// Created by Ross Butler on 04/06/2017.
// Copyright (c) 2017 Ross Butler. All rights reserved.
//
import UIKit
import TailorSwift
class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var debouncedButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
// MARK: View life cycle
override func viewDidLoad() {
// Example of trimming attributed text
let price: Double = 2.111111
let priceFormatter = PriceFormatter()
if let formattedPrice = priceFormatter.string(from: price) {
print(formattedPrice)
}
let originalString = " \n TailorSwift \n\n\n "
let trimmedString = originalString.trimmingCharacters(in: .whitespacesAndNewlines)
titleLabel.attributedText = NSAttributedString(string: trimmedString)
// Example of using UIColor extension to select a shade of a color
self.view.backgroundColor = UIColor.blue.shade(.darkest)
}
@IBAction func buttonTapped(_ button: UIButton) {
debouncedButton.debounce()
print("Button tapped!")
}
}
| true
|
6c340992e1524cb715179a432ced00c63ee77165
|
Swift
|
LeoDorbes/iFridge
|
/MyFridge/FridgeItemListSingleton.swift
|
UTF-8
| 1,878
| 3.21875
| 3
|
[] |
no_license
|
//
// Fridge.swift
// MyFridge
//
// Created by leo dorbes on 06/03/2017.
// Copyright © 2017 Léo Dorbes. All rights reserved.
//
import UIKit
class FridgeItemListSingleton {
private var items: [FridgeItem]
private var tenDaysItemsIndex : [Int] = []
static var instance = FridgeItemListSingleton()
private init() {
items = []
}
func getElementAt(row : Int) -> FridgeItem{
return self.items[row]
}
func getCount() -> Int {
return self.items.count
}
func init10Days(){
self.tenDaysItemsIndex = []
let date = Date()
var i = 0
var dateComponent = DateComponents()
dateComponent.day = 10
let futureDate = Calendar.current.date(byAdding: dateComponent, to: date)
for item in items{
i += 1
print(i)
if(item.getDate() < futureDate! && item.getDate() >= date){
self.tenDaysItemsIndex.append(i)
}
}
}
func count10Days()-> Int {
return self.tenDaysItemsIndex.count
}
func get10DaysAt(row : Int) -> FridgeItem{
let index = tenDaysItemsIndex[row]
return self.items[index - 1]
}
func removeAt(row : Int) {
self.items.remove(at: row)
}
func add(item : FridgeItem){
self.items.append(item)
}
func addCourseItems(){
for i in 0 ..< CourseItemListSingleton.instance.getCount(){
if(CourseItemListSingleton.instance.getElementAt(row: i).getState()){
let f: FridgeItem = FridgeItem(name: CourseItemListSingleton.instance.getElementAt(row: i).getName() )
FridgeItemListSingleton.instance.add(item: f)
}
}
CourseItemListSingleton.instance.removeAll()
}
}
| true
|
72d14a112cb0300f56830c07c4041471141fb749
|
Swift
|
codecat15/Youtube-tutorial
|
/SwiftUI/CombineApiSeries/LazyLoadingDemo/LazyLoadingDemo/Utilities/HttpUtility.swift
|
UTF-8
| 1,319
| 2.9375
| 3
|
[] |
no_license
|
//
// HttpUtility.swift
// LazyLoadingDemo
//
// Created by CodeCat15 on 7/4/21.
//
import Foundation
final class HttpUtility {
static let shared = HttpUtility()
private init(){}
func postData<T:Decodable>(request: URLRequest, resultType:T.Type, completionHandler:@escaping(_ reuslt: T?)-> Void) {
processRequest(request: request, resultType: resultType) { response in
_ = completionHandler(response)
}
}
func getData<T:Decodable>(request: URLRequest, resultType:T.Type, completionHandler:@escaping(_ reuslt: T?)-> Void) {
processRequest(request: request, resultType: resultType) { response in
_ = completionHandler(response)
}
}
private func processRequest<T:Decodable>(request: URLRequest,resultType:T.Type, completionHandler:@escaping(_ reuslt: T?)-> Void ) {
URLSession.shared.dataTask(with: request) { data, response, error in
if(error == nil && data != nil) {
do {
let response = try JSONDecoder().decode(resultType.self, from: data!)
_ = completionHandler(response)
} catch {
debugPrint("error occured \(error)")
_ = completionHandler(nil)}
}
}.resume()
}
}
| true
|
6463a7c43cd98729cf2db3d616b758db4636a8e8
|
Swift
|
PurpleDrinkz/Menu-Lugares-Restaurantes
|
/ViewControllers/ViewController2.swift
|
UTF-8
| 3,270
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController2.swift
// Tabs
//
// Created by Alumno on 10/10/18.
// Copyright © 2018 Benjamin. All rights reserved.
//
import Foundation
import UIKit
class ViewController2: UIViewController, UITableViewDataSource, UITableViewDelegate {
let restaurantes : [Restaurante] = [Restaurante(nombre: "The Stratosphere Restaurant", descripcion: "Have some drinks in the sky", imagenLista : UIImage(named: "stratophere")!, imagenDetalle : UIImage(named: "stratophere")!),
Restaurante(nombre: "Gordon Ramsey Restaurant", descripcion: "Have some angry god damn food", imagenLista : UIImage(named: "gordon")!, imagenDetalle : UIImage(named: "gordon")!),
Restaurante(nombre: "Bazaar Meat", descripcion: "Dedicated to the bounty of the earth", imagenLista : UIImage(named: "bazaar")!, imagenDetalle : UIImage(named: "bazaar")!),
Restaurante(nombre: "Carnevino", descripcion: "The name of Mario Batali and Joe Bastianich’s Italian-influenced steakhouse says it all.", imagenLista : UIImage(named: "carnevino")!, imagenDetalle : UIImage(named: "carnevino")!),
Restaurante(nombre: "Twist", descripcion: "Twist is breathtaking. There’s the airy dining room, with its glass orb chandeliers and serene decor.", imagenLista : UIImage(named: "twist")!, imagenDetalle : UIImage(named: "twist")!),]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let celda2 = tableView.dequeueReusableCell(withIdentifier: "cellRestaurante") as? CeldaRestaurante
celda2?.lblNombre.text = restaurantes[indexPath.row].nombre
celda2?.imgRestaurant.image = restaurantes[indexPath.row].imagenLista
return celda2!
}
//Aqui se establece el tamaño de las celdas
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 124.5
}
//Aquí se establece el titulo del table view
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "Restaurants"
}
@IBOutlet weak var tbRestaurantes: UITableView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//if segue.identifier == "goToDetalleRestaurante"{
let destino = segue.destination as! DetalleRestauranteController
destino.restaurante = restaurantes[(tbRestaurantes.indexPathForSelectedRow?.row)!]
//}
}
}
| true
|
3ef759f7acfbaebc3bde1e63e423e11bbcb42493
|
Swift
|
ZikeX/JDKit
|
/Extensions/CGFloat.swift
|
UTF-8
| 591
| 3.21875
| 3
|
[] |
no_license
|
import UIKit
extension CGFloat {
/// ZJaDe: 根据Self返回一个弧度
func toRadians() -> CGFloat {
return (CGFloat (M_PI) * self) / 180.0
}
/// ZJaDe: 根据Self返回一个弧度
func degreesToRadians() -> CGFloat {
return toRadians()
}
/// ZJaDe: 把本身,从角度转换成弧度
mutating func toRadiansInPlace() {
self = (CGFloat (M_PI) * self) / 180.0
}
/// ZJaDe: 根据angle返回一个弧度
func degreesToRadians (_ angle: CGFloat) -> CGFloat {
return (CGFloat (M_PI) * angle) / 180.0
}
}
| true
|
b7798492c06178450d36e787c635d224d04d3671
|
Swift
|
SAP/gigya-swift-sdk
|
/GigyaTfa/GigyaTfa/Utils/AlertControllerUtils.swift
|
UTF-8
| 1,153
| 3.03125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AlertControllerUtils.swift
// GigyaSwift
//
// Created by Shmuel, Sagi on 16/06/2019.
// Copyright © 2019 Gigya. All rights reserved.
//
import UIKit
class AlertControllerUtils {
static func show(vc: UIViewController, title: String, message: String, result: @escaping (Bool) -> Void) {
DispatchQueue.main.async {
// Create the alert controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: NSLocalizedString("Approve", comment: ""), style: .default) {
UIAlertAction in
result(true)
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Deny", comment: ""), style: .cancel) {
UIAlertAction in
result(false)
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
vc.present(alertController, animated: true, completion: nil)
}
}
}
| true
|
7c8f4c9fcef750e8b4965805423ea284f0f6a5b0
|
Swift
|
0xsoria/AnaliseDeSentimento
|
/Modules/Sources/FeatureTweets/TweetTableViewCell.swift
|
UTF-8
| 1,943
| 2.859375
| 3
|
[] |
no_license
|
//
// File.swift
//
//
// Created by Gabriel Soria Souza on 25/03/21.
//
import UIKit
final class TweetTableViewCell: UITableViewCell {
private let stack: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.alignment = .leading
stack.spacing = 10
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
private let userLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private let tweetLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupViews()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupText(user: String, tweet: String) {
self.userLabel.text = "@\(user)"
self.tweetLabel.text = tweet
}
private func setupViews() {
self.addSubview(self.stack)
self.stack.addArrangedSubview(self.userLabel)
self.stack.addArrangedSubview(self.tweetLabel)
self.stack.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
self.stack.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
self.stack.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
self.stack.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true
self.userLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
}
}
| true
|
efc3f7fa630e1eca30c7175f5cc96119b7ba340d
|
Swift
|
michael-perrone/EveryoneBooks-IOS-swift
|
/EveryoneBooks-IOS/View/GenericDropDown.swift
|
UTF-8
| 1,683
| 2.796875
| 3
|
[] |
no_license
|
//
// GenericDropDown.swift
// EveryoneBooks-IOS
//
// Created by Michael Perrone on 7/17/20.
// Copyright © 2020 Michael Perrone. All rights reserved.
//
import UIKit
class GenericDropDown: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource {
var data: [String] = [] {
didSet {
if data.count > 0 {
selectedItem = data[0];
DispatchQueue.main.async {
self.selectRow(0, inComponent: 0, animated: true)
}
}
DispatchQueue.main.async {
self.reloadAllComponents()
}
}
}
var selectedItem: String?;
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
dataSource = self;
delegate = self;
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1;
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return data.count;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if data.count > 0 {
return data[row];
}
else {
return "Not Good"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if data.count > 0 {
self.selectedItem = data[row];
}
}
func configureView() {
setHeight(height: 90);
}
}
| true
|
d2c590c6bb76c2df342f1f2d977bf7de2e494c98
|
Swift
|
PavelSnizhko/hw3
|
/thirdTask/thirdTask/ViewController.swift
|
UTF-8
| 4,215
| 2.828125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// thirdTask
//
// Created by Павел Снижко on 27.12.2020.
//
//
import UIKit
class ViewController: UIViewController {
var circle: UIView!
var randomColor: UIColor{
[UIColor.yellow, UIColor.orange, UIColor.red, UIColor.blue, UIColor.green, UIColor.purple].randomElement()!
}
override func viewDidLoad() {
super.viewDidLoad()
self.circle = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.circle.layer.cornerRadius = circle.frame.width * 0.5
self.circle.center = view.center
self.circle.backgroundColor = .red
view.addSubview(circle)
addSwipe()
addTaps()
}
func addSwipe() {
let directions: [UISwipeGestureRecognizer.Direction] = [.right, .left, .up, .down]
directions.forEach{ direction in
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture) )
gesture.direction = direction
view.addGestureRecognizer(gesture)
}
}
func addTaps() {
for count in 1...2 {
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTaps))
tap.numberOfTapsRequired = count
view.addGestureRecognizer(tap)
}
}
@objc func handleTaps(gesture: UITapGestureRecognizer) {
switch gesture.numberOfTapsRequired {
case 2:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2 )})
let animation = CAKeyframeAnimation()
animation.keyPath = "position"
animation.values = circlePath()
animation.duration = 3.0
self.circle.layer.add(animation, forKey: "position")
case 1:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2 )})
default:
break
}
}
@objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case .down:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.backgroundColor = self.randomColor
self.circle.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2 + 30)})
case .right:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.backgroundColor = self.randomColor
self.circle.center = CGPoint(x: self.view.frame.width / 2 + 30, y: self.view.frame.height / 2)
})
case .left:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.backgroundColor = self.randomColor
self.circle.center = CGPoint(x: self.view.frame.width / 2 - 30, y: self.view.frame.height / 2)})
case .up:
UIView.transition(with: self.circle, duration: 1.5, animations: {
self.circle.backgroundColor = self.randomColor
self.circle.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2 - 30)})
default:
break
}
}
}
func circlePath() -> [CGPoint] {
var pathArray = [CGPoint]()
let rightMoving = Double(self.view.frame.width / 4)
let downMoving = Double(self.view.frame.height / 4)
for angle in 0...360 {
let radian = Double(angle) * Double.pi / Double(180)
let x = 80.0 + 80.0 * sin(radian) + rightMoving
let y = 80.0 + 80.0 * cos(radian) + downMoving
pathArray.append(CGPoint(x: x, y: y))
}
return pathArray
}
}
| true
|
db84bc685fd6313b2e9f7e28b54e9c95bd5e4e62
|
Swift
|
Ciecs20171106520/-2
|
/冒泡排序2/main.swift
|
UTF-8
| 458
| 2.953125
| 3
|
[] |
no_license
|
//
// main.swift
// 冒泡排序2
//
// Created by s20171106520 on 2018/9/29.
// Copyright © 2018年 s20171106520. All rights reserved.
//
import Foundation
var i=0
var j=0
var k=0
var a:[Int] = [1000,188,7,226,5,2,3,13,12,0]
for i in (0 ..< 9)
{
for j in (0 ..< (9-i))
{
if a[j]>a[j+1]
{
k=a[j+1]
a[j+1]=a[j]
a[j]=k
}
}
}
for i in 0..<10
{
print("\(a[i])",terminator: " ")
}
| true
|
fc98d41cee5f76b2162bff8b2fb77a44cd091683
|
Swift
|
olgamart/vkApp
|
/vkApp/Models/Services/VKDataBD.swift
|
UTF-8
| 892
| 2.625
| 3
|
[] |
no_license
|
//
// VKDataBD.swift
// vkApp
//
// Created by Olga Martyanova on 05/08/2018.
// Copyright © 2018 olgamart. All rights reserved.
//
import Foundation
import RealmSwift
class VKDataBD {
class func saveData (saveObjects: [Object], type: Object.Type){
do {
// let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
// let realm = try Realm(configuration: config)
let realm = try! Realm()
let oldData = realm.objects(type)
realm.beginWrite()
realm.delete(oldData)
realm.add(saveObjects)
try realm.commitWrite()
} catch {
print(error)
}
}
class func loadData(type: Object.Type) -> [Object]{
let realm = try! Realm()
let loadObjects = realm.objects(type)
return Array(loadObjects)
}
}
| true
|
86f8e75fecbf16f2129652693e52ad84dacefe1c
|
Swift
|
sgsolo/storyes
|
/StoriesSDK/Classes/Common/Classes/AnimatedImageView.swift
|
UTF-8
| 2,667
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
enum AnimationMode {
case scaleAspectFill
case scale
case left
case right
}
final class AnimatedImageView: UIView {
var image: UIImage? {
get { return imageView.image }
set {
imageView.image = newValue
layoutImageView()
}
}
private let imageView = UIImageView()
init() {
self.animationMode = .scaleAspectFill
super.init(frame: .zero)
addSubview(imageView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutImageView()
}
var animationMode: AnimationMode {
didSet { layoutImageView() }
}
private func layoutImageView() {
guard let image = imageView.image else { return }
func layoutAspectFill() {
let widthRatio = imageToBoundsWidthRatio(image: image)
let heightRatio = imageToBoundsHeightRatio(image: image)
imageViewBoundsToSize(size: CGSize(width: image.size.width / min(widthRatio, heightRatio), height: image.size.height / min(widthRatio, heightRatio)))
centerImageView()
}
func layoutScale() {
let widthRatio = imageToBoundsWidthRatio(image: image)
let heightRatio = imageToBoundsHeightRatio(image: image)
let scaleFactor: CGFloat = 1.1
imageViewBoundsToSize(size: CGSize(width: image.size.width * scaleFactor / min(widthRatio, heightRatio), height: image.size.height * scaleFactor / min(widthRatio, heightRatio)))
centerImageView()
}
func layoutLeft() {
let widthRatio = imageToBoundsWidthRatio(image: image)
let heightRatio = imageToBoundsHeightRatio(image: image)
imageViewBoundsToSize(size: CGSize(width: image.size.width / min(widthRatio, heightRatio), height: image.size.height / min(widthRatio, heightRatio)))
}
func layoutRight() {
centerImageViewToPoint(point: CGPoint(x: bounds.width - imageView.frame.width / 2, y: imageView.frame.height / 2))
}
switch animationMode {
case .scaleAspectFill: layoutAspectFill()
case .scale: layoutScale()
case .left: layoutLeft()
case .right: layoutRight()
}
}
private func imageToBoundsWidthRatio(image: UIImage) -> CGFloat {
return image.size.width / bounds.size.width
}
private func imageToBoundsHeightRatio(image: UIImage) -> CGFloat {
return image.size.height / bounds.size.height
}
private func centerImageViewToPoint(point: CGPoint) {
imageView.center = point
}
private func imageViewBoundsToSize(size: CGSize) {
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
}
private func centerImageView() {
imageView.center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
}
}
| true
|
ed6f68aee98705a29e4c3fdafdd149198e03dc06
|
Swift
|
mproberts/RxSwiftCollections
|
/RxSwiftCollections/Classes/SimpleObservableList.swift
|
UTF-8
| 3,498
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// SimpleObservableList.swift
// RxSwiftCollections
//
// Created by Mike Roberts on 2018-05-19.
//
import Foundation
import RxSwift
/// A basic implementation of a mutable, reactive list. Standard sequence
/// operations can be used to apply changes to the list. When changes are
/// made, the list will emit updates to any listeners
public class SimpleObservableList<T>: ObservableList<T> {
private var currentList: [T]?
// private var updateQueue = [Update<T>]()
private let subject: PublishSubject<Update<T>> = PublishSubject()
private let queue = DispatchQueue(label: "SimpleObservableListQueue")
public override init() {
}
public init(_ values: [T]) {
self.currentList = values
}
public init(_ values: T...) {
self.currentList = values
}
private func update(_ updater: @escaping (([T]) -> Update<T>)) {
guard let update = queue.sync(execute: { () -> Update<T>? in
let listCopy = Array(self.currentList ?? [])
let update = updater(listCopy)
self.currentList = update.list.elements
return update
}) else {
return
}
self.subject.onNext(update)
}
public override var updates: Observable<Update<T>> {
return subject
.startWith(Update(list: currentList ?? [], changes: [.reload]))
.asObservable()
}
}
public extension SimpleObservableList {
/// Appends the supplied `element` to the current list
/// - parameters:
/// - element: The value to be added to the underlying sequence
func append(_ element: T) {
update { previous -> Update<T> in
var next = Array(previous)
next.append(element)
return Update(list: next, changes: [.insert(index: next.count - 1)])
}
}
func appendAll(_ elements: [T]) {
update { previous -> Update<T> in
var next = Array(previous)
next.append(contentsOf: elements)
var changes = [Change]()
for i in 0 ..< elements.count {
changes.append(.insert(index: previous.count + i))
}
return Update(list: next, changes: changes)
}
}
/// Inserts the supplied `element` in the current list, at the position specified
/// - parameters:
/// - element: The element to be added to the underlying sequence
/// - at: The position at which to add `element`
func insert(_ element: T, at: Int) {
update { previous -> Update<T> in
var next = Array(previous)
next.insert(element, at: at)
return Update(list: next, changes: [.insert(index: at)])
}
}
/// Removes the element from the current list, at the position specified
/// - parameters:
/// - at: The position at which to remove the existing element
func remove(at: Int) {
update { previous -> Update<T> in
var next = Array(previous)
next.remove(at: at)
return Update(list: next, changes: [.delete(index: at)])
}
}
/// Removes all elements from the current list
func removeAll() {
update { _ -> Update<T> in
return Update(list: [], changes: [.reload])
}
}
}
| true
|
13e9cb6a00d68a9982ad5b02761cce7d5bddf075
|
Swift
|
tarsbase/snake-playgroundbook
|
/Snake.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/06_Challenge.playgroundpage/Contents.swift
|
UTF-8
| 2,432
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
//#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
Congratulation! You have created the game Snake.
On the following page is a complete implementation with a new feature called Rainbow Mode 🌈
You can play around and try to beat your high score.
If you want to use this code to create your own Snake Game, you can the find the complete code in this Playground Book or on [GitHub](https://github.com/dnadoba/snake-playgroundbook)
*/
//#-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, hide)
//#-code-completion(bookauxiliarymodule, show)
//#-code-completion(identifier, show, UIColor)
//#-code-completion(identifier, hide, SnakeGameController, SnakeGame)
//#-code-completion(identifier, hide, Direction)
//#-code-completion(identifier, hide, ctrl)
//#-code-completion(identifier, hide, makeDefaultGame())
//#-code-completion(identifier, hide, didPassTests(), didMakeGrid(), didMakeSnake(), didPlaceCoin(), didCollectCoinInLastUpdate(), didExtendSnakeInLastUpdate(), initGameHints(), passTestOnce(), calledChangeSnakeFacingDirection, calledMoveSnakeInFacingDirection, gameStopped())
//#-code-completion(keyword, if, else, ||, return)
import PlaygroundSupport
//#-end-hidden-code
//#-editable-code
func initGame() {
makeGrid(width: 11, height: 11, wallColor: #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 1))
makeSnake(length: 4, tailColor: #colorLiteral(red: 0, green: 0.9768045545, blue: 0, alpha: 1), headColor: #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1))
placeRandomCoin(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1))
}
func didSwipe(in direction: Direction) {
changeSnakeFacingDirection(direction)
}
func update() {
if wallInFrontOfSnake() || snakeIntersectWithItself() {
gameOver()
return
}
if coinInFrontOfSnake() {
collectCoin()
extendSnakeInFacingDirection()
placeRandomCoin(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1))
} else {
moveSnakeInFacingDirection()
}
if collectedCoins >= 12 {
enableSnakeRainbowMode()
}
}
//#-end-editable-code
//#-hidden-code
ctrl.userInitCallback = initGame
ctrl.userSwipeCallback = didSwipe
ctrl.userUpdateCallback = update
PlaygroundPage.current.liveView = ctrl
//#-end-hidden-code
| true
|
01c2a6937c2efaddb9699c3c6fef4cff91d3b701
|
Swift
|
kpatel1989/SwiftLearning
|
/KpChapter8/KpChapter8/KpTime.swift
|
UTF-8
| 1,808
| 3.078125
| 3
|
[] |
no_license
|
//
// KpTime.swift
// KpChapter8
//
// Created by macadmin on 2016-10-06.
// Copyright © 2016 lambton. All rights reserved.
//
import Cocoa
open class KpTime: NSObject {
open var hour:Int = 0 {
willSet {
print("Hour is " + String(hour) + ", Setting it to " + String(newValue))
}
didSet {
if (hour < 0 || hour > 24) {
print("Hour should be between 0 and 24. Resetting it to \(oldValue)")
hour = oldValue
}
}
}
open var minute:Int = 0 {
willSet {
print("Hour is " + String(minute) + ", Setting it to " + String(newValue))
}
didSet {
if (minute < 0 || minute > 59) {
print("Hour should be between 0 and 24. Resetting it to \(oldValue)")
minute = oldValue
}
}
}
open var second:Int = 0 {
willSet {
print("Hour is " + String(second) + ", Setting it to " + String(newValue))
}
didSet {
if (second < 0 || second > 59) {
print("Hour should be between 0 and 24. Resetting it to \(oldValue)")
second = oldValue
}
}
}
override init() {
}
init?(hour:Int, minute:Int, second:Int) {
self.hour = hour
self.minute = minute
self.second = second
if (hour < 0 || hour > 24 || minute < 0 || minute > 59 || second < 0 || second > 59 ) {
return nil
}
}
open override var description: String {
return String(format: "%d:%2d:%2d:%@", (hour == 0 || hour == 12) ? 12 : hour % 12, minute, second, (hour < 12 ? "AM" : "PM"))
}
func printTime() {
print(description)
}
}
| true
|
7a0576312a8588147516a827f85551ae32281a40
|
Swift
|
daichao/Proficient-in-iOS-development
|
/Chapter8/Simple Table/Simple Table/ViewController.swift
|
UTF-8
| 2,975
| 2.953125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Simple Table
//
// Created by daichao on 16/4/11.
// Copyright © 2016年 com.daichao.*. All rights reserved.
//
import UIKit
class ViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{
private let dwarves=[
"Sleepy","Sneey","Bashful","Happy","Doc","Grumpy","Dopey","Thorin","Dorin","Nori","Ori","Balin","Dwalin","Fili","Kili","Oin","Gloin","Bifur","Bofur","Bombur"
]
let simpleTableIdentifier="SimpleTableIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dwarves.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier )
if(cell == nil){
cell=UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: simpleTableIdentifier)
}
let image=UIImage(named: "star")
cell?.imageView?.image=image
let highlightedImage=UIImage(named: "star2")
cell?.imageView?.highlightedImage=highlightedImage
if indexPath.row < 7 {
cell?.detailTextLabel?.text="Mr Disney"
}else{
cell?.detailTextLabel?.text="Mr Tolkien"
}
cell!.textLabel!.text=dwarves[indexPath.row]
cell?.textLabel?.font=UIFont.boldSystemFontOfSize(50)
return cell!
}
func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int {
return indexPath.row%4
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if indexPath.row==0{
return nil
}else if(indexPath.row%2==0){
return NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section)
}
else{
return indexPath
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rowValue=dwarves[indexPath.row]
let message="You selected \(rowValue)"
let controller=UIAlertController(title: "Row Selecter", message: message, preferredStyle: .Alert)
let action=UIAlertAction(title: "Yes ,I did", style: .Default, handler: nil)
controller.addAction(action)
presentViewController(controller, animated: true, completion: nil)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPath.row==0 ? 120 : 70
}
}
| true
|
0af0582af3c36ac9626f4e8a55cb5fc2dea6360f
|
Swift
|
nazmulcuet11/FoodTracker-Without-StoryBoard
|
/food-tracker/Views/MealTableViewCell.swift
|
UTF-8
| 2,109
| 2.71875
| 3
|
[] |
no_license
|
//
// MealTableView.swift
// food-tracker
//
// Created by Nazmul Islam on 16/4/18.
// Copyright © 2018 Nazmul Islam. All rights reserved.
//
import UIKit
import SnapKit
class MealTableViewCell: UITableViewCell {
//MARK: Properties
let mealPhoto: UIImageView = {
let imageView = UIImageView()
let defaultImage = UIImage(named: "meal1")
imageView.image = defaultImage
return imageView
}()
let nameLabel: UILabel = {
let label = UILabel()
label.text = "Meal Name"
return label
}()
let ratingControll: RatingControl = {
let ratingControl = RatingControl()
ratingControl.rating = 4
ratingControl.isUserInteractionEnabled = false
return ratingControl
}()
//MARK: Initializtions
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Private Methods
private func setUpViews() {
self.contentView.addSubview(self.mealPhoto)
self.contentView.addSubview(self.nameLabel)
self.contentView.addSubview(self.ratingControll)
self.mealPhoto.snp.makeConstraints { (make: ConstraintMaker) -> Void in
make.height.equalTo(90.0)
make.width.equalTo(90.0)
make.left.equalToSuperview()
make.top.equalToSuperview()
make.bottom.equalToSuperview()
}
self.nameLabel.snp.makeConstraints { (make: ConstraintMaker) -> Void in
make.left.equalTo(mealPhoto.snp.right).offset(8.0)
make.right.equalToSuperview().inset(8.0)
make.top.equalToSuperview().offset(8.0)
}
self.ratingControll.snp.makeConstraints { (make: ConstraintMaker) -> Void in
make.left.equalTo(mealPhoto.snp.right).offset(8.0)
make.bottom.equalToSuperview().inset(8.0)
}
}
}
| true
|
ab9f2705d18d42fee9f6cbf61214ab84a5e6739f
|
Swift
|
warkarth/diplomadoiOS
|
/week5/enums.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
|
UTF-8
| 946
| 3.796875
| 4
|
[
"MIT"
] |
permissive
|
//: [Previous](@previous)
import Foundation
class Alumno{
var numCuenta: String
fileprivate var nombre: String
private var sexo: String //V3 V4
open var rfc: String
var edad: Int{
willSet{
print("El nuevo valor sera: \(newValue)")
}
didSet{
print("Valor anterior: \(oldValue)")
print("Valor actual: \(edad)")
}
}
func estudia(){
print("Naaah no estudia")
}
init(numCuenta: String){
self.numCuenta = numCuenta
self.nombre = "Nobody"
self.sexo = "M"
self.rfc = "eoid4533193"
self.edad = 24
}
}
class Ingenieria: Alumno{
override func estudia() {
print("Si estudia")
}
}
class Contaduria: Alumno{
override func estudia() {
print("Efectivamente no estudia")
}
}
let parrita = Alumno(numCuenta: "99999999")
parrita.edad = 26
//: [Next](@next)
| true
|
b7cad1e061133a10f67f8de735c9895e69b57586
|
Swift
|
ThePowerOfSwift/VideoFilters
|
/VideoFilters/THAssetsLibrary.swift
|
UTF-8
| 2,570
| 2.625
| 3
|
[] |
no_license
|
//
// THAssetsLibrary.swift
// VideoFilters
//
// Created by Mohsin on 28/09/2015.
// Copyright (c) 2015 Mohsin. All rights reserved.
//
import UIKit
import AssetsLibrary
import AVFoundation
class THAssetsLibrary: NSObject {
var library : ALAssetsLibrary!
override init(){
super.init()
self.library = ALAssetsLibrary()
}
func writeImage(image : UIImage , complete : (success : Bool , error : NSError?) -> Void){
self.library.writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!, completionBlock: { (assetUrl, error) -> Void in
if error != nil{
complete(success: false, error: error)
}
else{
complete(success: true, error: nil)
}
})
}
func writeVideoAtURL(videoURL : NSURL, complete : (success : Bool , error : NSError?)->Void ){
if self.library.videoAtPathIsCompatibleWithSavedPhotosAlbum(videoURL){
self.library.writeVideoAtPathToSavedPhotosAlbum(videoURL, completionBlock: { (url, error) -> Void in
println("video write")
if error != nil {
complete(success: false, error: error)
}
else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
complete(success: true, error: nil)
})
}
})
}
}
// helper func
func generateThumbnailForVideoAtURL(videoUrl : NSURL , complete : (image: UIImage?) -> Void){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let asset = AVAsset.assetWithURL(videoUrl) as? AVAsset
var imageGenerator : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.maximumSize = CGSizeMake(100.0, 0.0)
imageGenerator.appliesPreferredTrackTransform = true
var cgImage : CGImage = imageGenerator.copyCGImageAtTime(kCMTimeZero, actualTime: nil, error: nil)
let image = UIImage(CGImage: cgImage)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println("image generated : \(image?.description)")
complete(image: image)
})
})
}
}
| true
|
b91a575698af0a369a53e8fb671abecc9144e3d0
|
Swift
|
uditsalwan/GithubAPIDemo
|
/GithubIssueViewer/Core/Network/CoreNetworking/APIError.swift
|
UTF-8
| 1,498
| 3.125
| 3
|
[
"CC-BY-3.0"
] |
permissive
|
//
// APIError.swift
// GithubIssueViewer
//
// Created by Udit on 21/06/19.
// Copyright © 2019 iOSDemo. All rights reserved.
//
import Foundation
/**
Error response model used to handle different errors throughout the application.
Errors can be:
- `mappingFailed` -
Mapping of server response to required model failed
- `invalidURL` -
Request builder failed to create a valid URL
- `emptyResponse` -
Response received from server does not contain data
- `noContent` -
204 Response received from server
- `badResponse` -
Error recieved from server or HTTP status code is not in valid range
- Tag: APIError
*/
public enum APIError : Error {
case mappingFailed
case invalidURL
case emptyResponse
case noContent
case badResponse(code: Int?, desc: String?)
}
extension APIError {
public var code: Int {
switch self {
case .badResponse(let code, _):
return code ?? 0
case .emptyResponse:
return -1
default:
return 0
}
}
public var description: String? {
switch self {
case .badResponse(_, let description):
return description ?? ""
default:
return nil
}
}
}
extension APIError: LocalizedError {
public var errorDescription: String? {
switch self {
case .badResponse(_, let description):
return description ?? "Error"
default:
return nil
}
}
}
| true
|
21ce24bb44490a00b405299b113c9d957f1c6789
|
Swift
|
andrewvy/swift-todo
|
/todolist/Classes/TodoDetailedViewController.swift
|
UTF-8
| 1,018
| 2.6875
| 3
|
[] |
no_license
|
//
// TodoDetailedView.swift
// todolist
//
// Created by Andrew Vy on 1/22/16.
// Copyright © 2016 Andrew Vy. All rights reserved.
//
import UIKit
class TodoDetailedViewController: UIViewController {
var todo: Todo
var label = UILabel()
var todoLabel = UILabel()
init(todo: Todo) {
self.todo = todo
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = "Todo:"
label.frame = CGRect(x: 10, y: 20, width: 150, height: 150)
label.font = UIFont(name: "HelveticaNeue", size: 36.0)
todoLabel.text = todo.label
todoLabel.frame = CGRect(x: 10, y: 65, width: 150, height: 150)
todoLabel.font = UIFont(name: "HelveticaNeue", size: 12.0)
view.addSubview(label)
view.addSubview(todoLabel)
view.backgroundColor = UIColor.whiteColor()
}
}
| true
|
e3fd6a5db787ff2dbdb5aa3ee1ab6649be3f7a51
|
Swift
|
lcs-bting/Santa
|
/Santa/ContentView.swift
|
UTF-8
| 1,405
| 2.890625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// Santa
//
// Created by Bill Ting on 2020-12-03.
//
import SwiftUI
struct ContentView: View {
@State var isActive = false
var body: some View {
NavigationView{
VStack{
Image("Santa")
.resizable()
.scaledToFit()
.frame(width: 3000, height: 150)
Text("Write a Letter To Santa")
.font(.title)
.fontWeight(.heavy)
.foregroundColor(Color.red)
Spacer()
Image("Text")
.resizable()
.scaledToFit()
NavigationLink(destination: Number_Generator(rootIsActive: $isActive), isActive: $isActive){
Image("Start")
.resizable()
.scaledToFit()
.padding()
}
.isDetailLink(false)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
ba4ca57aaf7f22ae2ffe98c2d919c12c65324c5a
|
Swift
|
knikandrov/MyTestRepo
|
/1-03 core concepts.playground/Pages/Bools.xcplaygroundpage/Contents.swift
|
UTF-8
| 2,598
| 4.59375
| 5
|
[] |
no_license
|
//: [Previous](@previous)
let yes = true
let no = false
let oneIsGreaterThanTwo = 1 > 2
let oneIsLessThanTwo = 1 < 2
6 >= 6
let oneEqualsTwo = 1 == 2
let catDoesNotEqualDog = "Cat" != "Dog"
let carComesBeforeCat = "Car" < "Cat"
let waterIsWet = true
let fireIsCold = false
let catsAreCute = true
!waterIsWet
let allAreTrue = waterIsWet && fireIsCold && catsAreCute
let anyAreTrue = waterIsWet || fireIsCold || catsAreCute
let andCombo = 1 < 2 && 4 < 3
let orCombo = "Cat" == "Dog" || "Godzilla" == "Godzilla"
let a = 5
let b = 10
let min = a < b ? a : b
/*:
### BOOLEANS
Create a constant called `myAge` and set it to your age. Then, create a constant called `isTeenager` that uses Boolean logic to determine if the age denotes someone in the age range of 13 to 19.
*/
// TODO: Write solution here
let myAge = 22
let isTeenager = myAge => 13 && myAge <= 19
/*:
Create another constant called `leonardosAge` and set it to 14, the age of Leonardo in the 1984 Teenage Mutant Ninja Turtles comic. Then, create a constant called `eitherAreTeenagers` that uses Boolean logic to determine if either you or Leonardo are teenagers.
*/
// TODO: Write solution here
let leonardosAge = 14
let eitherAreTeenagers = (myAge => 13 && myAge <= 19) || (leonardosAge => 13 && leonardosAge <= 19)
/*:
Create a constant called student and set it to your name as a string. Create a constant called author and set it to "Matt Galloway", the original author of these exercises. Create a constant called `authorIsStudent` that uses string equality to determine if student and author are equal.
*/
// TODO: Write solution here
let student = "Konstantin"
let author = "Matt Galloway"
let authorIsStudent = student == author
/*:
Create a constant called `studentBeforeAuthor` which uses string comparison to determine if student comes before author.
*/
// TODO: Write solution here
let studentBeforeAuthor = student < author
/*:
### IF STATEMENTS AND BOOLEANS
You've already created a constant called "myAge" and checked to see if you are a teenager. Using that information, write an if statement to print out "Teenager" if you're a teenager, and "Not a teenager" if you're not.
*/
// TODO: Write solution here
let checkTeenager = isTeenager ? "Teenager" : "Not a teenager"
/*:
Create a constant called `answer` and use a ternary conditional operator to check if you are *not* a teenager and set it equal the same strings you printed in the above exercise. Then print out answer.
*/
// TODO: Write solution here
let answer = isTeenager ? print("Teenager") : print ("Not a teenager")
//: [Next](@next)
| true
|
eddb0b554168bee011796650636feddf8521d0a6
|
Swift
|
deLore051/JewelleryStoreApplication
|
/Jewllery Store Application/Managers/ErrorManager.swift
|
UTF-8
| 1,204
| 2.78125
| 3
|
[] |
no_license
|
//
// ErrorManager.swift
// Jewllery Store Application
//
// Created by Stefan Dojcinovic on 8.8.21..
//
import Foundation
import UIKit
struct ErrorManager {
static func errorAlert(_ error : Error) -> UIAlertController {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: NSLocalizedString(
"OK",
comment: "Default action"),
style: .default,
handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
return alert
}
static func emptyFieldErrorAlert() -> UIAlertController {
let alert = UIAlertController(title: "Error", message: "All fields must be filled", preferredStyle: .alert)
alert.addAction(
UIAlertAction(title: NSLocalizedString(
"OK",
comment: "Default action"),
style: .default,
handler: { _ in
NSLog("The \"OK\" alert occured.")
}))
return alert
}
}
| true
|
51c2168699aada4410ee4ac4694a9155f65948fe
|
Swift
|
viWaveULife/rmhs-external-login
|
/iOS/RMHsExternalLoginIOSExample/RMHsExternalLoginIOSExample/ViewController.swift
|
UTF-8
| 3,260
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// RMHsExternalLoginIOSExample
//
// Created by kushim.chiang on 2020/9/15.
// Copyright © 2020 kushim.chiang. All rights reserved.
//
import UIKit
import WebKit
import SafariServices
enum ServerResponseMessage: String {
case BUSY
case NORMAL
}
let _applicationNameForUserAgent = "Version/8.0.2 Safari/600.2.5 RossmaxHealthStyleService iOS"
let _handlerName = "RMHs"
class ViewController: UIViewController {
// login url is provided by Rossmax / ViWaveULife.
let loginWebURLString = "https://rossmax-care-dev.web.app/outer_service_login"
// serviceId is provided by Rossmax / ViWaveULife.
let serviceId = "oService1"
var webView: WKWebView!
// MARK: - Life cycle functions
override func loadView() {
replaceViewByWebView()
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: loginWebURLString) {
webView.load(URLRequest(url: url))
}
}
// MARK: - Implementation functions
private func replaceViewByWebView() {
let userContentController = WKUserContentController()
userContentController.add(self, name: _handlerName)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
// for Google Auth on phone devices.
configuration.applicationNameForUserAgent = _applicationNameForUserAgent
webView = WKWebView(frame: .zero, configuration: configuration)
webView.navigationDelegate = self
view = webView
}
}
// MARK: -
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let messageBody = message.body as? String else {
return
}
switch messageBody {
case ServerResponseMessage.BUSY.rawValue:
// Timing to display UI "BUSY"
print("Show indicator start.")
case ServerResponseMessage.NORMAL.rawValue:
// Timing to display UI from BUSY to not.
print("Show indicator stop.")
default:
// After obtaining the access tokn, you can save it and switch to another display interface.
showAccessTokenByAlertController(messageBody)
}
}
/// Show access token by AlertController
///
/// This function is just a demo.
private func showAccessTokenByAlertController(_ messageBody: String) {
let titleString = "Access Token"
let alertController = UIAlertController(title: titleString, message: messageBody, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertController.addAction(okAction)
present(alertController, animated: true)
}
}
extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("setServiceId('\(serviceId)')") { (response, error) in
guard error == nil else {
return
}
}
}
}
| true
|
14700a68fa57bcc9818f43ae5389a327b1eca3b9
|
Swift
|
GustavoVergara/SwiftMailgun
|
/SwiftMailgun/Api/MailgunAPI.swift
|
UTF-8
| 4,878
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// MailgunAPI.swift
// SwiftMailgun
//
// Created by Christopher Jimenez on 3/7/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
//
// MandrillAPI.swift
// SwiftMandrill
//
// Created by Christopher Jimenez on 1/18/16.
// Copyright © 2016 greenpixels. All rights reserved.
//
import Alamofire
/// Mailgun API Class to be use to send emails
open class MailgunAPI {
private let apiKey: String
private let domain: String
/**
Inits the API with the ApiKey and client domain
- parameter apiKey: Api key to use the API
- parameter clientDomain: Client domain authorized to send your emails
- returns: MailGun API Object
*/
public init(apiKey: String, clientDomain: String) {
self.apiKey = apiKey
self.domain = clientDomain
}
/**
Sends an email with the provided parameters
- parameter to: email to
- parameter from: email from
- parameter subject: subject of the email
- parameter bodyHTML: html body of the email, can be also plain text
- parameter completionHandler: the completion handler
*/
open func sendEmail(to: String, from: String, subject: String, bodyHTML: String, completionHandler:@escaping (MailgunResult)-> Void) -> Void {
let email = MailgunEmail(to: to, from: from, subject: subject, html: bodyHTML)
self.sendEmail(email, completionHandler: completionHandler)
}
/**
Send the email with the email object
- parameter email: email object
- parameter completionHandler: completion handler
*/
open func sendEmail(_ email: MailgunEmail, completionHandler: @escaping (MailgunResult) -> Void) -> Void {
/// Serialize the object to an dictionary of [String:Anyobject]
guard let params = try? email.as([String : String].self) else {
completionHandler(MailgunResult(success: false, message: "Fail to parse MailgunEmail", id: nil))
return
}
//The mailgun API expect multipart params.
//Setups the multipart request
Alamofire.upload(
multipartFormData: { multipartFormData in
// add parameters as multipart form data to the body
for (key, value) in params {
multipartFormData.append(value.data(using: .utf8, allowLossyConversion: false)!, withName: key)
}
},
to: ApiRouter.sendEmail(self.domain).urlStringWithApiKey(self.apiKey),
encodingCompletion: { encodingResult in
switch encodingResult {
//Check if it works
case .success(let upload, _, _):
upload.responseData { response in
do {
var result = try JSONDecoder().decode(MailgunResult.self, from: response.result.unwrap())
result.success = true
completionHandler(result)
} catch {
print("error calling \(ApiRouter.sendEmail)")
let errorMessage = error.localizedDescription
if let data = response.data {
let errorData = String(data: data, encoding: String.Encoding.utf8)
print(errorData as Any)
}
let result = MailgunResult(success: false, message: errorMessage, id: nil)
completionHandler(result)
}
}
//Check if we fail
case .failure(let error):
print("error calling \(ApiRouter.sendEmail)")
print(error)
completionHandler(MailgunResult(success: false, message: "There was an error", id: nil))
return
}
}
)
}
//ApiRouter enum that will take care of the routing of the urls and paths of the API
private enum ApiRouter {
case sendEmail(String)
var path: String {
switch self{
case .sendEmail(let domain):
return "\(domain)/messages";
}
}
func urlStringWithApiKey(_ apiKey : String) -> URLConvertible {
//Builds the url with the API key
return "https://api:\(apiKey)@\(Constants.mailgunApiURL)/\(self.path)"
}
}
}
| true
|
4fc6ce3ebcae3aed592adf929b569ba85d364433
|
Swift
|
parth-tagline/RxSwift_DEMO
|
/RxSwift_DEMO/Data/NotesData.swift
|
UTF-8
| 488
| 2.71875
| 3
|
[] |
no_license
|
//
// NotesData.swift
// RxSwift_DEMO
//
// Created by tagline13 on 05/09/20.
// Copyright © 2020 tagline13. All rights reserved.
//
import Foundation
class NoteData : Codable {
var title: String = ""
var content: String = ""
var date: String = ""
var id : String = ""
init(id:String, title:String, content:String , date : String)
{
self.id = id
self.title = title
self.content = content
self.date = date
}
}
| true
|
66e5936eb0ee83b10907905b7200dd532c94e3c3
|
Swift
|
dunkelstern/UnchainedString
|
/UnchainedStringTests/split.swift
|
UTF-8
| 5,023
| 2.953125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
//
// UnchainedStringTests.swift
// UnchainedStringTests
//
// Created by Johannes Schriewer on 22/12/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import XCTest
@testable import UnchainedString
class splitTests: XCTestCase {
func testJoinWithString() throws {
let result = String.join(["Item 0", "Item 1", "Item 2"], delimiter: ", ")
XCTAssert(result == "Item 0, Item 1, Item 2")
}
func testJoinWithStringAndEmptyArray() throws {
let result = String.join([String](), delimiter: ", ")
XCTAssert(result == "")
}
func testJoinWithStringAndSingleItemArray() throws {
let result = String.join(["Test"], delimiter: ", ")
XCTAssert(result == "Test")
}
func testJoinWithEmptyString() throws {
let delim: String = ""
let result = String.join(["Item 0", "Item 1", "Item 2"], delimiter: delim)
XCTAssert(result == "Item 0Item 1Item 2")
}
func testJoinWithEmptyStringAndEmptyArray() throws {
let delim: String = ""
let result = String.join([String](), delimiter: delim)
XCTAssert(result == "")
}
func testJoinWithChar() throws {
let delim: Character = ","
let result = String.join(["Item 0", "Item 1", "Item 2"], delimiter: delim)
XCTAssert(result == "Item 0,Item 1,Item 2")
}
func testJoinWithCharAndEmptyArray() throws {
let delim: Character = ","
let result = String.join([String](), delimiter: delim)
XCTAssert(result == "")
}
func testJoin() throws {
let result = String.join(["Item 0", "Item 1", "Item 2"])
XCTAssert(result == "Item 0Item 1Item 2")
}
func testJoinWithEmptyArray() throws {
let result = String.join([String]())
XCTAssert(result == "")
}
func testSplitByDelimiterChar() throws {
let delim: Character = ","
let result = "Item 0,Item 1,Item 2".split(delim)
XCTAssert(result.count == 3)
if result.count == 3 {
XCTAssert(result[0] == "Item 0")
XCTAssert(result[1] == "Item 1")
XCTAssert(result[2] == "Item 2")
}
}
func testSplitByDelimiterCharAndEmptyString() throws {
let delim: Character = ","
let result = "".split(delim)
XCTAssert(result.count == 1)
if result.count == 1 {
XCTAssert(result[0] == "")
}
}
func testSplitByDelimiterCharMaxsplit() throws {
let delim: Character = ","
let result = "Item 0,Item 1,Item 2,Item 3".split(delim, maxSplits: 2)
XCTAssert(result.count == 3)
if result.count == 3 {
XCTAssert(result[0] == "Item 0")
XCTAssert(result[1] == "Item 1")
XCTAssert(result[2] == "Item 2,Item 3")
}
}
func testSplitByDelimiterString() throws {
let result = "Item 0, Item 1, Item 2".split(", ")
XCTAssert(result.count == 3)
if result.count == 3 {
XCTAssert(result[0] == "Item 0")
XCTAssert(result[1] == "Item 1")
XCTAssert(result[2] == "Item 2")
}
}
func testSplitByDelimiterStringAndEmptyString() throws {
let result = "".split(", ")
XCTAssert(result.count == 1)
if result.count == 1 {
XCTAssert(result[0] == "")
}
}
func testSplitByDelimiterStringMaxsplit() throws {
let result = "Item 0, Item 1, Item 2, Item 3".split(", ", maxSplits: 2)
XCTAssert(result.count == 3)
if result.count == 3 {
XCTAssert(result[0] == "Item 0")
XCTAssert(result[1] == "Item 1")
XCTAssert(result[2] == "Item 2, Item 3")
}
}
}
#if os(Linux)
extension splitTests {
static var allTests : [(String, splitTests -> () throws -> Void)] {
return [
("testJoinWithString", testJoinWithString),
("testJoinWithStringAndEmptyArray", testJoinWithStringAndEmptyArray),
("testJoinWithStringAndSingleItemArray", testJoinWithStringAndSingleItemArray),
("testJoinWithEmptyString", testJoinWithEmptyString),
("testJoinWithEmptyStringAndEmptyArray", testJoinWithEmptyStringAndEmptyArray),
("testJoinWithChar", testJoinWithChar),
("testJoinWithCharAndEmptyArray", testJoinWithCharAndEmptyArray),
("testJoin", testJoin),
("testJoinWithEmptyArray", testJoinWithEmptyArray),
("testSplitByDelimiterChar", testSplitByDelimiterChar),
("testSplitByDelimiterCharAndEmptyString", testSplitByDelimiterCharAndEmptyString),
("testSplitByDelimiterCharMaxsplit", testSplitByDelimiterCharMaxsplit),
("testSplitByDelimiterString", testSplitByDelimiterString),
("testSplitByDelimiterStringAndEmptyString", testSplitByDelimiterStringAndEmptyString),
("testSplitByDelimiterStringMaxsplit", testSplitByDelimiterStringMaxsplit)
]
}
}
#endif
| true
|
a2e94e84305b0b644c6c518eb6a0add73b105617
|
Swift
|
bolagadalla/Destini
|
/Destini-iOS13/Controller/ViewController.swift
|
UTF-8
| 898
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Destini-iOS13
//
// Created by Bola Gadalla on 9/12/19.
// Copyright © 2019 Bola Gadalla. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var storyLabel: UILabel!
@IBOutlet weak var choice1Button: UIButton!
@IBOutlet weak var choice2Button: UIButton!
var storyBrain = StoryBrain()
override func viewDidLoad()
{
super.viewDidLoad()
UpdateUI()
}
@IBAction func ChoicePressed(_ sender: UIButton)
{
let choiceText = sender.currentTitle!
storyBrain.GetNextStory(userChoice: choiceText)
UpdateUI()
}
func UpdateUI()
{
storyLabel.text = storyBrain.GetStoryTitle()
choice1Button.setTitle(storyBrain.GetChoice1(), for: .normal)
choice2Button.setTitle(storyBrain.GetChoice2(), for: .normal)
}
}
| true
|
10bd059ed287c9925110205169691c0ce663fae0
|
Swift
|
hvaghasia/WeatherApp
|
/WeatherApp/UI/View/TableViewCell/ForecastTableViewCell.swift
|
UTF-8
| 764
| 2.796875
| 3
|
[] |
no_license
|
//
// ForecastTableViewCell.swift
// WeatherApp
//
// Created by admin on 11/10/18.
// Copyright © 2018 Ugam. All rights reserved.
//
import UIKit
class ForecastTableViewCell: UITableViewCell {
// MARK: - UI Elements
@IBOutlet private weak var minimumTemperatureLabel: UILabel!
@IBOutlet private weak var maximumTemperatureLabel: UILabel!
var viewModel: ForecastCellViewModel? {
didSet {
parseViewModel()
}
}
}
// MARK: - Private
extension ForecastTableViewCell {
private func parseViewModel() {
guard let viewModel = viewModel else { return }
minimumTemperatureLabel.text = viewModel.minimumTemperature
maximumTemperatureLabel.text = viewModel.maximumTemperature
}
}
| true
|
5f8d664055a5a8c20d81fc58676650c764b36b30
|
Swift
|
redroostertech/rooted
|
/Rooted MessagesExtension/Models/MeetingTimeLength.swift
|
UTF-8
| 636
| 2.609375
| 3
|
[] |
no_license
|
//
// MeetingTimeLength.swift
// Rooted MessagesExtension
//
// Created by Michael Westbrooks on 2/26/20.
// Copyright © 2020 RedRooster Technologies Inc. All rights reserved.
//
import Foundation
import ObjectMapper
class MeetingTimeLength: Mappable {
var id: Int?
var length: Int?
var name: String?
var type: String?
required init?(map: Map) { }
func mapping(map: Map) {
id <- map["id"]
length <- map["length"]
name <- map["name"]
type <- map["type"]
}
}
extension MeetingTimeLength: Equatable {
static func == (lhs: MeetingTimeLength, rhs: MeetingTimeLength) -> Bool {
return lhs.id == rhs.id
}
}
| true
|
e8ddd205a4223b569da7cbaf9e85380ff6a7d396
|
Swift
|
gabrielPeart/PopcornTimeTV
|
/PopcornTime/Movie+Torrents.swift
|
UTF-8
| 424
| 2.5625
| 3
|
[] |
no_license
|
//
// Movie+Torrents.swift
// PopcornTime
//
// Created by Tengis Batsaikhan on 25/06/2016.
// Copyright © 2016 PopcornTime. All rights reserved.
//
import PopcornKit
extension Movie {
var torrentsText: String {
let filteredTorrents: [String] = torrents.map { torrent in
return "quality=\(torrent.quality)&hash=\(torrent.hash)"
}
return filteredTorrents.joinWithSeparator("•")
}
}
| true
|
aeac50325deffc56872c4ea3b622891988eef240
|
Swift
|
heestand-xyz/TriangleDraw-iOS
|
/Source/TriangleDrawTests/Tests/E2CanvasPointOrientationTests.swift
|
UTF-8
| 1,273
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
// MIT license. Copyright (c) 2020 TriangleDraw. All rights reserved.
import XCTest
@testable import TriangleDrawLibrary
class E2CanvasPointOrientationTests: XCTestCase {
func testUpward() {
let canvas: E2Canvas = loadCanvas("test_orientation_upward.pbm")
var countUpward: UInt = 0
var countDownward: UInt = 0
for y in 0..<canvas.height {
for x in 0..<canvas.width {
let point = E2CanvasPoint(x: Int(x), y: Int(y))
let value: UInt8 = canvas.getPixel(point)
if value == 0 {
continue
}
switch point.orientation {
case .upward:
countUpward += 1
case .downward:
countDownward += 1
}
}
}
XCTAssertEqual(countUpward, 7)
XCTAssertEqual(countDownward, 0)
}
func testDownward() {
let canvas: E2Canvas = loadCanvas("test_orientation_downward.pbm")
var countUpward: UInt = 0
var countDownward: UInt = 0
for y in 0..<canvas.height {
for x in 0..<canvas.width {
let point = E2CanvasPoint(x: Int(x), y: Int(y))
let value: UInt8 = canvas.getPixel(point)
if value == 0 {
continue
}
switch point.orientation {
case .upward:
countUpward += 1
case .downward:
countDownward += 1
}
}
}
XCTAssertEqual(countUpward, 0)
XCTAssertEqual(countDownward, 7)
}
}
| true
|
c8ff4963a8667462b86bd2f4616d7cd28b78ddbf
|
Swift
|
JackZhao98/dots-ios
|
/Dots/Dots/Views/Components/CircleView.swift
|
UTF-8
| 1,784
| 3.546875
| 4
|
[
"Apache-2.0"
] |
permissive
|
//
// CircleView.swift
// Dots
//
// Created by Jack Zhao on 1/11/21.
//
import SwiftUI
/// A circular icon that is used to represent each individual.
struct CircleView: View {
/// Index of the circular icon
let index: Int
/// Diameter of the circular icon
let diameter: Double
/// Deprecated: Boolean value that decides whether the circle has ring.
let hasRing: Bool
/// Radius of the circle.
private let radius: CGFloat
private let ringStroke: Double
/// Initialize `CircleView`.
/// - Parameters:
/// - index: index that represents the dot.
/// - diameter: diameter of the dot.
/// - hasRing: Deprecated: Boolean value that decides whether the circle has ring.
/// - ringStroke: Size of the stroke.
init (index: Int = 0, diameter: Double = 30, hasRing: Bool = false, ringStroke: Double = 8) {
self.index = index
self.diameter = diameter
self.hasRing = hasRing
self.ringStroke = ringStroke
self.radius = self.hasRing ? CGFloat(diameter - self.ringStroke) : CGFloat(diameter)
}
/// Circle body view.
var body: some View {
ZStack {
if (self.hasRing) {
Circle()
.foregroundColor(.white)
.frame(width: CGFloat(self.diameter), height: CGFloat(self.diameter))
}
Circle()
.foregroundColor(classic.dotColors[index])
.frame(width: self.radius, height: self.radius)
}
}
}
struct CircleView_Previews: PreviewProvider {
static var previews: some View {
CircleView(index: 1, diameter: 30, hasRing: false, ringStroke: 8)
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
}
}
| true
|
16e0a7fd916f4733f0bf660d7c6789df7395a65f
|
Swift
|
hpbl/iOSJornada2017
|
/Exercícios/Aula 03/Resoluções Aula 03.playground/Contents.swift
|
UTF-8
| 3,293
| 3.9375
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
// Exercício 06
enum Movimento {
case pedra
case papel
case tesoura
}
enum Resultado {
case vitoria
case derrota
case empate
}
func partida(primeiroJogador: Movimento, segundoJogador: Movimento) -> Resultado {
if primeiroJogador == segundoJogador {
return .empate
} else if primeiroJogador == .pedra && segundoJogador == .tesoura ||
primeiroJogador == .papel && segundoJogador == .pedra ||
primeiroJogador == .tesoura && segundoJogador == .papel {
return .vitoria
} else {
return .derrota
}
}
partida(primeiroJogador: .pedra, segundoJogador: .tesoura) // -> "Você ganhou"
// Exercício 07
class Veiculo {
var velocidade: Int
func calcularTempo(_ distancia: Int) -> Int {
return distancia / self.velocidade
}
init(velocidade: Int) {
self.velocidade = velocidade
}
}
class VeiculoAquatico: Veiculo {
var largura: Double
init(largura: Double, velocidade: Int) {
self.largura = largura
super.init(velocidade: velocidade)
}
}
class VeiculoTerrestre: Veiculo {
var rodas: Int
init(rodas: Int, velocidade: Int) {
self.rodas = rodas
super.init(velocidade: velocidade)
}
}
class Carro: VeiculoTerrestre {
var janelas: Int
init(janelas: Int, rodas: Int, velocidade: Int) {
self.janelas = janelas
super.init(rodas: rodas, velocidade: velocidade)
}
/*init(janelas: Int, velocidade: Int) {
self.janelas = janelas
super.init(rodas: 4, velocidade: velocidade)
}*/
}
class Motocicleta: VeiculoTerrestre { }
class Barco: VeiculoAquatico {
var janelas: Int
init(janelas: Int, largura: Double, velocidade: Int) {
self.janelas = janelas
super.init(largura: largura, velocidade: velocidade)
}
}
// Deveria ser Carro ou VeiculoTerrestre?
class Onibus: Carro {
var capacidade: Int
init(capacidade: Int, velocidade: Int, rodas: Int, janelas: Int) {
self.capacidade = capacidade
super.init(janelas: janelas, rodas: rodas, velocidade: velocidade)
}
}
class Navio: VeiculoAquatico { }
// Exercício 08
protocol Forma {
func area() -> Float
func perimetro() -> Float
}
class Quadrado: Forma {
var lado: Float
init(lado: Float) {
self.lado = lado
}
func area() -> Float {
return self.lado * self.lado
}
func perimetro() -> Float {
return self.lado * 4
}
}
class Circulo: Forma {
var raio: Float
init(raio: Float) {
self.raio = raio
}
func area() -> Float {
return Float.pi * (self.raio * self.raio)
}
func perimetro() -> Float {
return 2 * Float.pi * self.raio
}
}
class Retangulo: Forma {
var base: Float
var altura: Float
init(base: Float, altura: Float) {
self.altura = altura
self.base = base
}
func area() -> Float {
return self.base * self.altura
}
func perimetro() -> Float {
return (self.base * 2) + (self.altura * 2)
}
}
| true
|
23892d85d19ac307b84cde3344e094cba9310422
|
Swift
|
djalfirevic/SwiftUI-Playground
|
/Big Mountain Studio/SwiftUI Animations/SwiftUIAnimations/SpringAnimations/Spring/Spring_Dampen.swift
|
UTF-8
| 2,017
| 3.28125
| 3
|
[] |
no_license
|
//
// Spring_Dampen.swift
// SwiftUIAnimations
//
// Created by Mark Moeykens on 9/30/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct Spring_Dampen: View {
@State private var show = false
@State private var dampingFraction = 0.825 // This is the default damping fraction
var body: some View {
ZStack {
RadialGradient(gradient: Gradient(colors: [Color("Dark"), Color("Darkest")]), center: .center, startRadius: 10, endRadius: 400)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 10) {
TitleText("Spring").foregroundColor(Color("Gold"))
SubtitleText("Dampen")
BannerText("Spring animations have a dampen property that dampens or make your spring less strong or intense.", backColor: Color("Gold"))
RoundedRectangle(cornerRadius: 40)
.fill(Color("Gold"))
.overlay(Image("Phone"))
.padding()
.scaleEffect(show ? 1 : 0.01, anchor: .bottom)
.opacity(show ? 1 : 0)
.animation(.spring(dampingFraction: self.dampingFraction)) // Adjust the "springiness"
Button(action: {
self.show.toggle()
}, label: {
Image(systemName: show ? "person.2.fill" : "person.2")
.foregroundColor(Color("Gold"))
.font(.largeTitle)
}).accentColor(Color("Accent"))
HStack {
Image(systemName: "0.circle.fill")
Slider(value: $dampingFraction)
Image(systemName: "1.circle.fill")
}.foregroundColor(Color("Gold")).padding()
}.font(.title)
}
}
}
struct Spring_Dampen_Previews: PreviewProvider {
static var previews: some View {
Spring_Dampen()
}
}
| true
|
606f554726ce3026c176a9e448cad251643dfbfc
|
Swift
|
bthomp22/swift-dictionary-lab-swift-intro-000
|
/DictionaryChallenge/Challenges.swift
|
UTF-8
| 1,989
| 3.65625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
//
// Challenges.swift
// DictionaryChallenge
//
// Created by Jim Campagno on 12/22/16.
// Copyright © 2016 Jim Campagno. All rights reserved.
//
import Foundation
class Challenges {
func createStatesAndCapitals() -> [String : String]{
let statesAndCapitals = ["New York": "Albany", "Ohio": "Columbus", "Florida":"Tallahassee", "Georgia": "Atlanta", "Kentucky": "Frankfort"]
return statesAndCapitals
}
func floridaCapital() -> String?{
let stateDictionary = createStatesAndCapitals()
return stateDictionary["Florida"]
}
func createFloridaCapitalSentence() -> String{
if let name = floridaCapital() {
return "The capital of Florida is \(name)."
} else {
return "Unable to find the capital of Florida"
}
}
func pennsylvaniaCapital() -> String?{
let stateDictionary = createStatesAndCapitals()
return stateDictionary["Pennsylvania"]
}
func createPennsylvaniaSentence() -> String{
if let name = pennsylvaniaCapital(){
return "The capital of Pennsylvania is \(name)"
} else {
return "Unable to find the capital of Pennsylvania."
}
}
func createAllStatesAndCapitals() -> [String: String]{
var newDictionary = createStatesAndCapitals()
newDictionary["Pennsylvania"] = "Harrisburg"
return newDictionary
}
func removePennsylvania() -> [String: String]{
var noPenn = createAllStatesAndCapitals()
noPenn["Pennsylvania"] = nil
return noPenn
}
func createBand() -> [String: [String]]{
let nirv = ["Kurt Cobain", "Krist Novoselic", "Dave Grohl"]
let beat = ["John Lennon", "George Harrison", "Paul McCartney", "Ringo Starr"]
let breed = ["Kim Deal", "Kelley Deal", "Josephine Wiggs", "Jim Macpherson"]
let bands = ["Nirvana": nirv, "The Beatles": beat, "The Breeders": breed]
return bands
}
// Answer the problems here.
}
| true
|
dbf74499cb78197d935241c90696fb82711d00f4
|
Swift
|
Adster94/FitnessAppRepo
|
/FitnessApp/WorkoutSelectionTableViewController.swift
|
UTF-8
| 5,773
| 2.890625
| 3
|
[] |
no_license
|
//
// WorkoutSelectionTableViewController.swift
// FitnessApp
//
// Created by Adam Moorey on 11/01/2017.
// Copyright © 2017 Adam Moorey. All rights reserved.
//
import UIKit
import os.log
class WorkoutSelectionTableViewController: UITableViewController
{
var workouts = [Workout]()
var selectedWorkout: Workout?
override func viewDidLoad()
{
super.viewDidLoad()
//load any saved workouts, otherwise load sample data
if let savedWorkouts = loadWorkouts()
{
workouts += savedWorkouts
}
else
{
//load sample workouts
loadSampleWorkouts()
}
}
func loadSampleWorkouts()
{
//create three basic workouts for displaying in the cells
let image1 = UIImage(named: "Cardio")!
let exercise1 = Exercise(name: "5 minute sprint", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Small sprint")
let exercise2 = Exercise(name: "30 minute long run", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Long run")
let exercise3 = Exercise(name: "5 minute sprint", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Small sprint")
let exercise4 = Exercise(name: "10 minute on/off run", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "On/off sprint")
var exerciseList1 = [Exercise]()
exerciseList1.append(exercise1!)
exerciseList1.append(exercise2!)
exerciseList1.append(exercise3!)
exerciseList1.append(exercise4!)
let workout1 = Workout(name: "Cardio Workout", image: image1, rating: 4, exercise: exerciseList1, identifier: "completeCardio")!
let image2 = UIImage(named: "Bicep Curls")!
let exercise5 = Exercise(name: "Bicep Curls x4", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Four bicep curls")
let exercise6 = Exercise(name: "Bar bicep curl x3", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Three barbell bicep curls")
let exercise7 = Exercise(name: "Bicep Curl to failure", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Bicep curls until you can't")
var exerciseList2 = [Exercise]()
exerciseList2.append(exercise5!)
exerciseList2.append(exercise6!)
exerciseList2.append(exercise7!)
let workout2 = Workout(name: "Bicep Workout", image: image2, rating: 3, exercise: exerciseList2, identifier: "completeBicep")!
let image3 = UIImage(named: "Endurance Cardio")!
let exercise8 = Exercise(name: "60 minute long run", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Extra Long run")
let exercise9 = Exercise(name: "60 minute cycle", image: #imageLiteral(resourceName: "DefaultImage"), length: 30, exerciseDescription: "Extra Long cycle")
var exerciseList3 = [Exercise]()
exerciseList3.append(exercise8!)
exerciseList3.append(exercise9!)
let workout3 = Workout(name: "Endurance Cardio", image: image3, rating: 3, exercise: exerciseList3, identifier: "completeEndurance")!
workouts += [workout1, workout2, workout3]
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int
{
//returns 1 section within the table
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
//returns the number of workouts within the list
return workouts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
//table view cells are reused and should be dequeued using a cell identifier
let cellIdentifier = "WorkoutTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! WorkoutTableViewCell
//fetches the appropriate workout for the data source layout
let workout = workouts[indexPath.row]
let tempString = String(workout.exercises.count)
//sets the values of the current cell to their correct list counterpart
cell.nameLabel.text = workout.name
cell.photoImageView.image = workout.image
cell.ratingControl.rating = workout.rating
cell.exerciseNumber.text = tempString + " exercises"
return cell
}
// MARK: - Navigation
//in a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
super.prepare(for: segue, sender: sender)
//get the cell that generated this segue
if let selectedWorkoutCell = sender as? WorkoutTableViewCell
{
let indexPath = tableView.indexPath(for: selectedWorkoutCell)!
let chosenWorkout = workouts[indexPath.row]
selectedWorkout = chosenWorkout
}
}
@IBAction func cancel(_ sender: UIBarButtonItem)
{
self.dismiss(animated: true, completion: nil)
}
//MARK: - Private Methods
private func loadWorkouts() -> [Workout]?
{
//return the array of workouts
return NSKeyedUnarchiver.unarchiveObject(withFile: Workout.ArchiveURL.path) as? [Workout]
}
}
| true
|
34b12bd4f73f4ac936f2ed88823d43641cb6731f
|
Swift
|
netguru-college/ios-lodz19-command
|
/Project/Source Files/Screens/Details/DetailInformationView.swift
|
UTF-8
| 1,939
| 2.828125
| 3
|
[] |
no_license
|
//
// DetailInformationView.swift
// NetguruCollegeApp
//
import Foundation
import UIKit
class DetailInformationView: UIView {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = #colorLiteral(red: 0.9369841218, green: 0.3454609811, blue: 0.1157674268, alpha: 1)
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
private let valueLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func feedWithValueString(valueString: String) {
valueLabel.text = valueString
}
init(iconName: String) {
super.init(frame: .zero)
imageView.image = UIImage(named: iconName)
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
addSubview(imageView)
addSubview(valueLabel)
NSLayoutConstraint.activate([
imageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8),
imageView.topAnchor.constraint(equalTo: self.topAnchor),
imageView.rightAnchor.constraint(equalTo: self.valueLabel.leftAnchor, constant: 8),
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
imageView.widthAnchor.constraint(equalToConstant: 30),
imageView.heightAnchor.constraint(equalToConstant: 30),
imageView.rightAnchor.constraint(equalTo: valueLabel.leftAnchor),
valueLabel.rightAnchor.constraint(equalTo: self.rightAnchor),
valueLabel.topAnchor.constraint(equalTo: self.topAnchor),
valueLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
| true
|
2c1a45c57f3dbddecd91ae51cecf8160ab50f4da
|
Swift
|
patagoniacode/soto
|
/Sources/Soto/Services/TranscribeStreamingService/TranscribeStreamingService_Error.swift
|
UTF-8
| 3,281
| 2.5625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for TranscribeStreamingService
public struct TranscribeStreamingServiceErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case internalFailureException = "InternalFailureException"
case limitExceededException = "LimitExceededException"
case serviceUnavailableException = "ServiceUnavailableException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize TranscribeStreamingService
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// One or more arguments to the StartStreamTranscription or StartMedicalStreamTranscription operation was invalid. For example, MediaEncoding was not set to a valid encoding, or LanguageCode was not set to a valid code. Check the parameters and try your request again.
public static var badRequestException: Self { .init(.badRequestException) }
/// A new stream started with the same session ID. The current stream has been terminated.
public static var conflictException: Self { .init(.conflictException) }
/// A problem occurred while processing the audio. Amazon Transcribe or Amazon Transcribe Medical terminated processing. Try your request again.
public static var internalFailureException: Self { .init(.internalFailureException) }
/// You have exceeded the maximum number of concurrent transcription streams, are starting transcription streams too quickly, or the maximum audio length of 4 hours. Wait until a stream has finished processing, or break your audio stream into smaller chunks and try your request again.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// Service is currently unavailable. Try your request later.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
}
extension TranscribeStreamingServiceErrorType: Equatable {
public static func == (lhs: TranscribeStreamingServiceErrorType, rhs: TranscribeStreamingServiceErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension TranscribeStreamingServiceErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| true
|
36b16c7ac4af4f43673713f2a960922a9273647c
|
Swift
|
JosueCuberoSanchez/iOS_Swift_Examples
|
/FromScratch/StarWarsApp/StarWarsApp/Views/AuthenticationViews/LoginView/LoginViewModel.swift
|
UTF-8
| 1,308
| 2.796875
| 3
|
[] |
no_license
|
//
// LoginViewModel.swift
// StarWarsApp
//
// Created by Josue on 1/25/19.
// Copyright © 2019 Josue. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
class LoginViewModel {
// Inputs
var email = PublishRelay<String>()
var password = PublishRelay<String>()
var loginTrigger = PublishRelay<Void>()
var loginSuccess: Driver<LoginResponse>
var loginFailure: Driver<Error?>
init(request: @escaping (_ body: [String: Any]) -> Driver<Response<LoginResponse>>) {
loginSuccess = Driver.empty()
loginFailure = Driver.empty()
let credentialsBody =
Observable.combineLatest(email.asObservable(), password.asObservable()) { (email, password) in
return ["email": email, "password": password]
}
// Simulate the api call
let sharedRequest = loginTrigger
.withLatestFrom(credentialsBody)
.flatMapLatest { request($0) }
.share()
let credentialsResponse = sharedRequest.mapSuccess()
let errorResponse = sharedRequest.mapError()
loginSuccess = credentialsResponse.map { $0 }.asDriver(onErrorDriveWith: Driver.empty())
loginFailure = errorResponse.map { $0 }.asDriver(onErrorDriveWith: Driver.empty())
}
}
| true
|
1e9260ed5e25fdae080a7e70f36c7f8bb4221609
|
Swift
|
stephyang/student_test
|
/student_test/studentscore.swift
|
UTF-8
| 349
| 2.59375
| 3
|
[] |
no_license
|
//
// studentscore.swift
// student_test
//
// Created by stephanie yang on 2016/3/13.
// Copyright © 2016年 stephanie yang. All rights reserved.
//
import Foundation
struct Student {
var name: String
var score: Int
}
struct Class {
var students:[Student]=[
Student(name: "Monkey", score:100 ),
Student(name: "Steph", score: 90)
]
}
| true
|
7d6ac954092feb9289661013eb6194018537d92f
|
Swift
|
dhirajjadhao/Noon-Twitter
|
/Noon Twitter/Tweet.swift
|
UTF-8
| 1,334
| 2.859375
| 3
|
[] |
no_license
|
//
// Tweet.swift
// Noon Twitter
//
// Created by Dhiraj Jadhao on 09/11/16.
// Copyright © 2016 Dhiraj Jadhao. All rights reserved.
//
import Foundation
import ObjectMapper
import AlamofireObjectMapper
class Tweet: Mappable {
//MARK: Properties
var name: String = ""
var handle: String = ""
var createdAt:String = ""
var body: String = ""
var profileImageURL: String = ""
var retweetCount:Int = 0
var likeCount:Int = 0
//MARK: Initialization
init(name: String, handle: String, createdAt: String, body: String, profileImageURL: String, retweetCount: Int,likeCount: Int) {
self.name = name
self.handle = handle
self.createdAt = createdAt
self.body = body
self.profileImageURL = profileImageURL
self.retweetCount = retweetCount
self.likeCount = likeCount
}
//MARK: Mapping
public required init?(map: Map) {}
func mapping(map: Map) {
name <- map["user.name"]
handle <- map["user.screen_name"]
createdAt <- map["created_at"]
body <- map["text"]
profileImageURL <- map["user.profile_image_url_https"]
retweetCount <- map["retweet_count"]
likeCount <- map["favorite_count"]
}
}
| true
|
a066314394569027607970e6dc1b1c365013cad0
|
Swift
|
brwong20/Apps-iOS
|
/Weather/Weather/NetworkOperation.swift
|
UTF-8
| 1,488
| 3.203125
| 3
|
[] |
no_license
|
//
// NetworkOperation.swift
// Weather
//
// Created by Brian Wong on 9/29/15.
// Copyright © 2015 Brian Wong. All rights reserved.
//
import Foundation
class NetworkOperation{
//Only initialized when class is called
lazy var session = NSURLSession.sharedSession()
let queryURL: NSURL
typealias JSONDictionaryCompletion = ([String:AnyObject]?) -> Void
init(url:NSURL){
self.queryURL = url
}
func downloadJSONFromURL(completion: JSONDictionaryCompletion) {
let request = NSURLRequest(URL: self.queryURL)
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
//Check the status code to see if request was successful. If it was, create a JSON object
do{
if let httpResponse = response as? NSHTTPURLResponse{
switch(httpResponse.statusCode){
case 200:
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject]
completion(jsonDictionary)
default:
print("Status code not successful: \(httpResponse.statusCode)")
}
} else {
print("Error: Not a valid HTTP response")
}
}catch{
}
}
dataTask.resume()
}
}
| true
|
221758628aac93c73442819ee2b73f986e30a111
|
Swift
|
Raafas/HaveIBeenPwned
|
/pwned/terminalUtils.swift
|
UTF-8
| 1,032
| 3.0625
| 3
|
[] |
no_license
|
//
// terminalUtils.swift
// pwned
//
// Created by Rafael Leandro on 02/08/18.
// Copyright © 2018 Rafael Leandro. All rights reserved.
//
import Foundation
extension String {
public enum Color: String {
case red = "\u{001B}[0;31m"
case green = "\u{001B}[0;32m"
case yellow = "\u{001B}[0;33m"
case blue = "\u{001B}[0;34m"
case white = "\u{001B}[0;37m"
}
public enum Style: String {
case none = "\u{001B}[0m"
case bold = "\u{001B}[1m"
case dim = "\u{001B}[2m"
case underline = "\u{001B}[4m"
case blink = "\u{001B}[5m"
case inverted = "\u{001B}[7m"
case hidden = "\u{001B}[8m"
}
func AnsiString(color: Color = .white, style: Style = .none) -> String {
return "\(style.rawValue)\(color.rawValue)\(self)\(Color.white.rawValue)\(Style.none.rawValue)"
}
var withoutHtmlTags: String {
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
| true
|
ce1a84adbb7d8ce00fc99e16ce25f9b3491e6d06
|
Swift
|
hootsuite/token-ui
|
/Sources/TokenTextViewController.swift
|
UTF-8
| 37,459
| 2.9375
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright © 2017 Hootsuite. All rights reserved.
import Foundation
import UIKit
/// The delegate used to handle user interaction and enable/disable customization to a `TokenTextViewController`.
public protocol TokenTextViewControllerDelegate: AnyObject {
/// Called when text changes.
func tokenTextViewDidChange(_ sender: TokenTextViewController)
/// Whether an edit should be accepted.
func tokenTextViewShouldChangeTextInRange(_ sender: TokenTextViewController, range: NSRange, replacementText text: String) -> Bool
/// Called when a token was tapped.
func tokenTextViewDidSelectToken(_ sender: TokenTextViewController, tokenRef: TokenReference, fromRect rect: CGRect)
/// Called when a token was deleted.
func tokenTextViewDidDeleteToken(_ sender: TokenTextViewController, tokenRef: TokenReference)
/// Called when a token was added.
func tokenTextViewDidAddToken(_ sender: TokenTextViewController, tokenRef: TokenReference)
/// Called when the formatting is being updated.
func tokenTextViewTextStorageIsUpdatingFormatting(_ sender: TokenTextViewController, text: String, searchRange: NSRange) -> [(attributes: [NSAttributedString.Key: Any], forRange: NSRange)]
/// Allows to customize the background color for a token.
func tokenTextViewBackgroundColourForTokenRef(_ sender: TokenTextViewController, tokenRef: TokenReference) -> UIColor?
/// Allows to customize the foreground color for a token
func tokenTextViewForegroundColourForTokenRef(_ sender: TokenTextViewController, tokenRef: TokenReference) -> UIColor?
/// Whether the last edit should cancel token editing.
func tokenTextViewShouldCancelEditingAtInsert(_ sender: TokenTextViewController, newText: String, inputText: String) -> Bool
/// Whether content of type type can be pasted in the text view.
/// This method is called every time some content may be pasted.
func tokenTextView(_: TokenTextViewController, shouldAcceptContentOfType type: PasteboardItemType) -> Bool
/// Called when media items have been pasted.
func tokenTextView(_: TokenTextViewController, didReceive items: [PasteboardItem])
}
/// Default implementation for some `TokenTextViewControllerDelegate` methods.
public extension TokenTextViewControllerDelegate {
/// Default value of `false`.
func tokenTextView(_: TokenTextViewController, shouldAcceptContentOfType type: PasteboardItemType) -> Bool {
return false
}
/// Empty default implementation.
func tokenTextView(_: TokenTextViewController, didReceive items: [PasteboardItem]) {
}
/// Empty default implementation
func tokenTextViewDidAddToken(_ sender: TokenTextViewController, tokenRef: TokenReference) {
}
/// Default color of white.
func tokenTextViewForegroundColourForTokenRef(_ sender: TokenTextViewController, tokenRef: TokenReference) -> UIColor? {
return .white
}
}
/// The delegate used to handle text input in a `TokenTextViewController`.
public protocol TokenTextViewControllerInputDelegate: AnyObject {
/// Called whenever the text is updated.
func tokenTextViewInputTextDidChange(_ sender: TokenTextViewController, inputText: String)
/// Called when the text is confirmed by the user.
func tokenTextViewInputTextWasConfirmed(_ sender: TokenTextViewController)
/// Called when teh text is cancelled by the user.
func tokenTextViewInputTextWasCanceled(_ sender: TokenTextViewController, reason: TokenTextInputCancellationReason)
}
/// Determines different input cancellation reasons for a `TokenTextViewController`.
public enum TokenTextInputCancellationReason {
case deleteInput
case tapOut
}
/// A data structure to hold constants for the `TokenTextViewController`.
public struct TokenTextViewControllerConstants {
public static let tokenAttributeName = NSAttributedString.Key(rawValue: "com.hootsuite.token")
static let inputTextAttributeName = NSAttributedString.Key(rawValue: "com.hootsuite.input")
static let inputTextAttributeAnchorValue = "anchor"
static let inputTextAttributeTextValue = "text"
}
public typealias TokenReference = String
/// A data structure used to identify a `Token` inside some text.
public struct TokenInformation {
/// The `Token` identifier.
public var reference: TokenReference
/// The text that contains the `Token`.
public var text: String
/// The range of text that contains the `Token`.
public var range: NSRange
}
/// Used to display a `UITextView` that creates and responds to `Token`'s as the user types and taps.
open class TokenTextViewController: UIViewController, UITextViewDelegate, NSLayoutManagerDelegate, TokenTextViewTextStorageDelegate, UIGestureRecognizerDelegate {
/// The delegate used to handle user interaction and enable/disable customization.
open weak var delegate: TokenTextViewControllerDelegate?
/// The delegate used to handle text input.
open weak var inputDelegate: TokenTextViewControllerInputDelegate? {
didSet {
if let (inputText, _) = tokenTextStorage.inputTextAndRange() {
inputDelegate?.tokenTextViewInputTextDidChange(self, inputText: inputText)
}
}
}
/// The font for the textView.
open var font = UIFont.preferredFont(forTextStyle: .body) {
didSet {
viewAsTextView.font = font
tokenTextStorage.font = font
}
}
/// Flag for text tokenization when input field loses focus
public var tokenizeOnLostFocus = false
fileprivate var tokenTapRecognizer: UITapGestureRecognizer?
fileprivate var inputModeHandler: TokenTextViewControllerInputModeHandler!
fileprivate var textTappedHandler: ((UITapGestureRecognizer) -> Void)?
fileprivate var inputIsSuspended = false
/// Initializer for `self`.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Initializer for `self`.
public init() {
super.init(nibName: nil, bundle: nil)
inputModeHandler = TokenTextViewControllerInputModeHandler(tokenTextViewController: self)
textTappedHandler = normalModeTapHandler
}
/// Loads a `PasteMediaTextView` as the base view of `self`.
override open func loadView() {
let textStorage = TokenTextViewTextStorage()
textStorage.formattingDelegate = self
let layoutManager = TokenTextViewLayoutManager()
layoutManager.delegate = self
let container = NSTextContainer(size: CGSize.zero)
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
textStorage.addLayoutManager(layoutManager)
let textView = PasteMediaTextView(frame: CGRect.zero, textContainer: container)
textView.delegate = self
textView.mediaPasteDelegate = self
textView.isScrollEnabled = true
tokenTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TokenTextViewController.textTapped(_:)))
tokenTapRecognizer!.numberOfTapsRequired = 1
tokenTapRecognizer!.delegate = self
textView.addGestureRecognizer(tokenTapRecognizer!)
self.view = textView
}
fileprivate var viewAsTextView: UITextView! {
return (view as! UITextView)
}
fileprivate var tokenTextStorage: TokenTextViewTextStorage {
return viewAsTextView.textStorage as! TokenTextViewTextStorage
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewAsTextView.font = font
NotificationCenter.default.addObserver(
self,
selector: #selector(TokenTextViewController.preferredContentSizeChanged(_:)),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil)
}
@objc func preferredContentSizeChanged(_ notification: Notification) {
tokenTextStorage.updateFormatting()
}
@objc func textTapped(_ recognizer: UITapGestureRecognizer) {
textTappedHandler?(recognizer)
}
// MARK: UIGestureRecognizerDelegate
/// Enables/disables some gestures to be recognized simultaneously.
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == tokenTapRecognizer {
return true
}
return false
}
// MARK: UITextView variables and functions.
/// The text contained in the textView.
open var text: String! {
get {
return viewAsTextView.text
}
set {
viewAsTextView.text = newValue
}
}
/// The color of the text in the textView.
open var textColor: UIColor! {
get {
return viewAsTextView.textColor
}
set {
viewAsTextView.textColor = newValue
tokenTextStorage.textColor = newValue
}
}
/// The style of the text alignment for the textView.
open var textAlignment: NSTextAlignment {
get {
return viewAsTextView.textAlignment
}
set {
viewAsTextView.textAlignment = newValue
}
}
/// The selected range of text in the textView.
open var selectedRange: NSRange {
get {
return viewAsTextView.selectedRange
}
set {
viewAsTextView.selectedRange = newValue
}
}
/// The type of keyboard displayed when the user interacts with the textView.
open var keyboardType: UIKeyboardType {
get {
return viewAsTextView.keyboardType
}
set {
viewAsTextView.keyboardType = newValue
}
}
/// The edge insets of the textView.
open var textContainerInset: UIEdgeInsets {
get {
return viewAsTextView.textContainerInset
}
set {
viewAsTextView.textContainerInset = newValue
}
}
/// Sets the scrolling enabled/disabled state of the textView.
open var scrollEnabled: Bool {
get {
return viewAsTextView.isScrollEnabled
}
set {
viewAsTextView.isScrollEnabled = newValue
}
}
/// The line fragment padding for the textView.
open var lineFragmentPadding: CGFloat {
get {
return viewAsTextView.textContainer.lineFragmentPadding
}
set {
viewAsTextView.textContainer.lineFragmentPadding = newValue
}
}
/// A rectangle that defines the area for drawing the caret in the textView.
public var cursorRect: CGRect? {
if let selectedTextRange = viewAsTextView.selectedTextRange {
return viewAsTextView.caretRect(for: selectedTextRange.start)
}
return nil
}
/// The accessibility label string for the text view.
override open var accessibilityLabel: String! {
get {
return viewAsTextView.accessibilityLabel
}
set {
viewAsTextView.accessibilityLabel = newValue
}
}
/// Assigns the first responder to the textView.
override open func becomeFirstResponder() -> Bool {
return viewAsTextView.becomeFirstResponder()
}
/// Resigns the first responder from the textView.
override open func resignFirstResponder() -> Bool {
return viewAsTextView.resignFirstResponder()
}
/// Resigns as first responder.
open func suspendInput() {
_ = resignFirstResponder()
inputIsSuspended = true
}
/// The text storage object holding the text displayed in this text view.
open var attributedString: NSAttributedString {
return viewAsTextView.textStorage
}
// MARK: Text manipulation.
/// Appends the given text to the textView and repositions the cursor at the end.
open func appendText(_ text: String) {
viewAsTextView.textStorage.append(NSAttributedString(string: text))
repositionCursorAtEndOfRange()
}
/// Adds text to the beginning of the textView and repositions the cursor at the end.
open func prependText(_ text: String) {
let cursorLocation = viewAsTextView.selectedRange.location
viewAsTextView.textStorage.insert(NSAttributedString(string: text), at: 0)
viewAsTextView.selectedRange = NSRange(location: cursorLocation + (text as NSString).length, length: 0)
repositionCursorAtEndOfRange()
}
/// Replaces the first occurrence of the given string in the textView with another string.
open func replaceFirstOccurrenceOfString(_ string: String, withString replacement: String) {
let cursorLocation = viewAsTextView.selectedRange.location
let searchRange = viewAsTextView.textStorage.mutableString.range(of: string)
if searchRange.length > 0 {
viewAsTextView.textStorage.mutableString.replaceCharacters(in: searchRange, with: replacement)
if cursorLocation > searchRange.location {
viewAsTextView.selectedRange = NSRange(location: min(cursorLocation + (replacement as NSString).length - (string as NSString).length, (text as NSString).length), length: 0)
repositionCursorAtEndOfRange()
}
}
}
/// Replaces the characters in the given range in the textView with the provided string.
open func replaceCharactersInRange(_ range: NSRange, withString: String) {
if !rangeIntersectsToken(range) {
viewAsTextView.textStorage.replaceCharacters(in: range, with: withString)
}
}
/// Inserts the given string at the provided index location of the textView.
open func insertString(_ string: String, atIndex index: Int) {
viewAsTextView.textStorage.insert(NSAttributedString(string: string), at: index)
}
// MARK: token editing
/// Adds a token to the textView at the given index and informs the delegate.
@discardableResult
open func addToken(_ startIndex: Int, text: String) -> TokenInformation {
let effectiveText = effectiveTokenDisplayText(text)
let attrs = createNewTokenAttributes()
let attrString = NSAttributedString(string: effectiveText, attributes: attrs)
viewAsTextView.textStorage.insert(attrString, at: startIndex)
repositionCursorAtEndOfRange()
let tokenRange = tokenAtLocation(startIndex)!.range
let tokenRef = attrs[TokenTextViewControllerConstants.tokenAttributeName] as! TokenReference
let tokenInfo = TokenInformation(reference: tokenRef, text: effectiveText, range: tokenRange)
delegate?.tokenTextViewDidChange(self)
delegate?.tokenTextViewDidAddToken(self, tokenRef: tokenRef)
return tokenInfo
}
/// Updates the formatting of the textView.
open func updateTokenFormatting() {
tokenTextStorage.updateFormatting()
}
fileprivate func createNewTokenAttributes() -> [NSAttributedString.Key: Any] {
return [
TokenTextViewControllerConstants.tokenAttributeName: UUID().uuidString as TokenReference
]
}
/// Updates the given `Token`'s text with the provided text and informs the delegate of the change.
open func updateTokenText(_ tokenRef: TokenReference, newText: String) {
let effectiveText = effectiveTokenDisplayText(newText)
replaceTokenText(tokenRef, newText: effectiveText)
repositionCursorAtEndOfRange()
self.delegate?.tokenTextViewDidChange(self)
}
/// Delegates the given `Token` and informs the delegate of the change.
open func deleteToken(_ tokenRef: TokenReference) {
replaceTokenText(tokenRef, newText: "")
viewAsTextView.selectedRange = NSRange(location: viewAsTextView.selectedRange.location, length: 0)
self.delegate?.tokenTextViewDidChange(self)
delegate?.tokenTextViewDidDeleteToken(self, tokenRef: tokenRef)
}
fileprivate func replaceTokenText(_ tokenToReplaceRef: TokenReference, newText: String) {
tokenTextStorage.enumerateTokens { (tokenRef, tokenRange) -> ObjCBool in
if tokenRef == tokenToReplaceRef {
self.viewAsTextView.textStorage.replaceCharacters(in: tokenRange, with: newText)
return true
}
return false
}
}
fileprivate func repositionCursorAtEndOfRange() {
let cursorLocation = viewAsTextView.selectedRange.location
if let tokenInfo = tokenAtLocation(cursorLocation) {
viewAsTextView.selectedRange = NSRange(location: tokenInfo.range.location + tokenInfo.range.length, length: 0)
}
}
/// An array of all the `Token`'s currently in the textView.
open var tokenList: [TokenInformation] {
return tokenTextStorage.tokenList
}
fileprivate func tokenAtLocation(_ location: Int) -> TokenInformation? {
for tokenInfo in tokenList {
if location >= tokenInfo.range.location && location < tokenInfo.range.location + tokenInfo.range.length {
return tokenInfo
}
}
return nil
}
/// Determines whether the given range intersects with a `Token` currently in the textView.
open func rangeIntersectsToken(_ range: NSRange) -> Bool {
return tokenTextStorage.rangeIntersectsToken(range)
}
/// Determines whether the given range intersects with a `Token` that is currently being input by the user.
open func rangeIntersectsTokenInput(_ range: NSRange) -> Bool {
return tokenTextStorage.rangeIntersectsTokenInput(range)
}
fileprivate func cancelEditingAndKeepText() {
tokenTextStorage.clearEditingAttributes()
inputDelegate?.tokenTextViewInputTextWasCanceled(self, reason: .tapOut)
}
// MARK: Token List editing
// Create a token from editable text contained from atIndex to toIndex (excluded)
fileprivate func tokenizeEditableText(at range: NSRange) {
if range.length != 0 {
let nsText = text as NSString
replaceCharactersInRange(range, withString: "")
let textSubstring = nsText.substring(with: range).trimmingCharacters(in: .whitespaces)
if !textSubstring.isEmpty {
addToken(range.location, text: textSubstring)
}
}
}
// Create tokens from all editable text contained in the input field
public func tokenizeAllEditableText() {
var nsText = text as NSString
if tokenList.isEmpty {
tokenizeEditableText(at: NSRange(location: 0, length: nsText.length))
return
}
// ensure we use a sorted tokenlist (by location)
let orderedTokenList: [TokenInformation] = tokenList.sorted(by: { $0.range.location < $1.range.location })
// find text discontinuities, characters that do not belong to a token
var discontinuities: [NSRange] = []
// find discontinuities before token list
guard let firstToken = orderedTokenList.first else { return }
if firstToken.range.location != 0 {
discontinuities.append(NSRange(location: 0, length: firstToken.range.location))
}
// find discontinuities within token list
for i in 1..<orderedTokenList.count {
let endPositionPrevious = orderedTokenList[i-1].range.length + orderedTokenList[i-1].range.location
let startPositionCurrent = orderedTokenList[i].range.location
if startPositionCurrent != endPositionPrevious {
// found discontinuity
discontinuities.append(NSRange(location: endPositionPrevious, length: (startPositionCurrent - endPositionPrevious)))
}
}
// find discontinuities after token list
guard let lastToken = orderedTokenList.last else { return }
let lengthAfterTokenList = lastToken.range.location + lastToken.range.length - nsText.length
if lengthAfterTokenList != 0 {
discontinuities.append(NSRange(location: (lastToken.range.length + lastToken.range.location), length: (nsText.length - lastToken.range.length - lastToken.range.location)))
}
// apply tokens at discontinuities
for i in (0..<discontinuities.count).reversed() {
// insert all new chips
tokenizeEditableText(at: discontinuities[i])
}
// move cursor to the end
nsText = text as NSString
selectedRange = NSRange(location: nsText.length, length: 0)
}
// Create editable text from exisitng token, appended to end of input field
// This method tokenizes all current editable text prior to making token editable
public func makeTokenEditableAndMoveToFront(tokenReference: TokenReference) {
var clickedTokenText = ""
guard let foundToken = tokenList.first(where: { $0.reference == tokenReference }) else { return }
clickedTokenText = foundToken.text.trimmingCharacters(in: CharacterSet.whitespaces)
tokenizeAllEditableText()
deleteToken(tokenReference)
appendText(clickedTokenText)
let nsText = self.text as NSString
selectedRange = NSRange(location: nsText.length, length: 0)
_ = becomeFirstResponder()
delegate?.tokenTextViewDidChange(self)
}
// MARK: Input Mode
///
open func switchToInputEditingMode(_ location: Int, text: String, initialInputLength: Int = 0) {
let attrString = NSAttributedString(string: text, attributes: [TokenTextViewControllerConstants.inputTextAttributeName: TokenTextViewControllerConstants.inputTextAttributeAnchorValue])
tokenTextStorage.insert(attrString, at: location)
if initialInputLength > 0 {
let inputRange = NSRange(location: location + (text as NSString).length, length: initialInputLength)
tokenTextStorage.addAttributes([TokenTextViewControllerConstants.inputTextAttributeName: TokenTextViewControllerConstants.inputTextAttributeTextValue], range: inputRange)
}
viewAsTextView.selectedRange = NSRange(location: location + (text as NSString).length + initialInputLength, length: 0)
viewAsTextView.autocorrectionType = .no
viewAsTextView.delegate = inputModeHandler
textTappedHandler = inputModeTapHandler
delegate?.tokenTextViewDidChange(self)
tokenTextStorage.updateFormatting()
}
/// Sets the text tap handler with the `normalModeTapHandler` and returns the location of the cursor.
open func switchToNormalEditingMode() -> Int {
var location = selectedRange.location
if let (_, anchorRange) = tokenTextStorage.anchorTextAndRange() {
location = anchorRange.location
replaceCharactersInRange(anchorRange, withString: "")
}
if let (_, inputRange) = tokenTextStorage.inputTextAndRange() {
replaceCharactersInRange(inputRange, withString: "")
}
viewAsTextView.delegate = self
textTappedHandler = normalModeTapHandler
viewAsTextView.autocorrectionType = .default
return location
}
fileprivate var normalModeTapHandler: ((UITapGestureRecognizer) -> Void) {
return { [weak self] recognizer in
self?.normalModeTap(recognizer: recognizer)
}
}
fileprivate var inputModeTapHandler: ((UITapGestureRecognizer) -> Void) {
return { [weak self] recognizer in
self?.inputModeTap(recognizer: recognizer)
}
}
fileprivate func normalModeTap(recognizer: UITapGestureRecognizer) {
viewAsTextView.becomeFirstResponder()
let location: CGPoint = recognizer.location(in: viewAsTextView)
if let charIndex = viewAsTextView.characterIndexAtLocation(location), charIndex < viewAsTextView.textStorage.length - 1 {
var range = NSRange(location: 0, length: 0)
if let tokenRef = viewAsTextView.attributedText?.attribute(TokenTextViewControllerConstants.tokenAttributeName, at: charIndex, effectiveRange: &range) as? TokenReference {
_ = resignFirstResponder()
let rect: CGRect = {
if let textRange = viewAsTextView.textRangeFromNSRange(range) {
return view.convert(viewAsTextView.firstRect(for: textRange), from: viewAsTextView.textInputView)
} else {
return CGRect(origin: location, size: CGSize.zero)
}
}()
delegate?.tokenTextViewDidSelectToken(self, tokenRef: tokenRef, fromRect: rect)
}
}
}
fileprivate func inputModeTap(recognizer: UITapGestureRecognizer) {
guard !inputIsSuspended else {
inputIsSuspended = false
return
}
let location: CGPoint = recognizer.location(in: viewAsTextView)
if
let charIndex = viewAsTextView.characterIndexAtLocation(location),
let (_, inputRange) = tokenTextStorage.inputTextAndRange(),
let (_, anchorRange) = tokenTextStorage.anchorTextAndRange(),
charIndex < anchorRange.location || charIndex >= inputRange.location + inputRange.length - 1
{
cancelEditingAndKeepText()
}
}
// MARK: UITextViewDelegate
open func textViewDidChange(_ textView: UITextView) {
self.delegate?.tokenTextViewDidChange(self)
}
open func textViewDidChangeSelection(_ textView: UITextView) {
if viewAsTextView.selectedRange.length == 0 {
// The cursor is being repositioned
let cursorLocation = textView.selectedRange.location
let newCursorLocation = clampCursorLocationToToken(cursorLocation)
if newCursorLocation != cursorLocation {
viewAsTextView.selectedRange = NSRange(location: newCursorLocation, length: 0)
}
} else {
// A selection range is being modified
let adjustedSelectionStart = clampCursorLocationToToken(textView.selectedRange.location)
let adjustedSelectionLength = max(adjustedSelectionStart, clampCursorLocationToToken(textView.selectedRange.location + textView.selectedRange.length)) - adjustedSelectionStart
if (adjustedSelectionStart != textView.selectedRange.location) || (adjustedSelectionLength != textView.selectedRange.length) {
viewAsTextView.selectedRange = NSRange(location: adjustedSelectionStart, length: adjustedSelectionLength)
}
}
}
fileprivate func clampCursorLocationToToken(_ cursorLocation: Int) -> Int {
if let tokenInfo = tokenAtLocation(cursorLocation) {
let range = tokenInfo.range
return (cursorLocation > range.location + range.length / 2) ? (range.location + range.length) : range.location
}
return cursorLocation
}
/// Determines whether the text in the given range should be replaced by the provided string.
/// Deleting one character, if it is part of a token, should delete the full token.
/// If the editing range intersects tokens, make sure tokens are fully deleted and delegate called.
open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText: String) -> Bool {
if range.length == 1 && (replacementText as NSString).length == 0 {
// Deleting one character, if it is part of a token the full token should be deleted
if let tokenInfo = tokenAtLocation(range.location) {
deleteToken(tokenInfo.reference)
viewAsTextView.selectedRange = NSRange(location: tokenInfo.range.location, length: 0)
return false
}
} else if range.length > 0 {
// Check if partial overlap or editing range contained in a token, reject edit
if !tokenTextStorage.isValidEditingRange(range) {
return false
}
// If the editing range intersects tokens, make sure tokens are fully deleted and delegate called
let intersectingTokenReferences = tokenTextStorage.tokensIntersectingRange(range)
if !intersectingTokenReferences.isEmpty {
replaceRangeAndIntersectingTokens(range, intersectingTokenReferences: intersectingTokenReferences, replacementText: replacementText)
self.delegate?.tokenTextViewDidChange(self)
return false
}
}
return delegate?.tokenTextViewShouldChangeTextInRange(self, range: range, replacementText: replacementText) ?? true
}
fileprivate func replaceRangeAndIntersectingTokens(_ range: NSRange, intersectingTokenReferences: [TokenReference], replacementText: String) {
viewAsTextView.textStorage.replaceCharacters(in: range, with: replacementText)
tokenTextStorage.enumerateTokens { (tokenRef, tokenRange) -> ObjCBool in
if intersectingTokenReferences.contains(tokenRef) {
self.viewAsTextView.textStorage.replaceCharacters(in: tokenRange, with: "")
}
return false
}
viewAsTextView.selectedRange = NSRange(location: viewAsTextView.selectedRange.location, length: 0)
for tokenRef in intersectingTokenReferences {
delegate?.tokenTextViewDidDeleteToken(self, tokenRef: tokenRef)
}
}
public func textViewDidEndEditing(_ textView: UITextView) {
if tokenizeOnLostFocus {
tokenizeAllEditableText()
}
}
// MARK: NSLayoutManagerDelegate
open func layoutManager(_ layoutManager: NSLayoutManager, shouldBreakLineByWordBeforeCharacterAt charIndex: Int) -> Bool {
var effectiveRange = NSRange(location: 0, length: 0)
if (view as! UITextView).attributedText?.attribute(TokenTextViewControllerConstants.tokenAttributeName, at: charIndex, effectiveRange: &effectiveRange) is TokenReference {
return false
}
return true
}
// MARK: TokenTextViewTextStorageDelegate
func textStorageIsUpdatingFormatting(_ sender: TokenTextViewTextStorage, text: String, searchRange: NSRange) -> [(attributes: [NSAttributedString.Key: Any], forRange: NSRange)]? {
return delegate?.tokenTextViewTextStorageIsUpdatingFormatting(self, text: text, searchRange: searchRange)
}
func textStorageBackgroundColourForTokenRef(_ sender: TokenTextViewTextStorage, tokenRef: TokenReference) -> UIColor? {
return delegate?.tokenTextViewBackgroundColourForTokenRef(self, tokenRef: tokenRef)
}
func textStorageForegroundColourForTokenRef(_ sender: TokenTextViewTextStorage, tokenRef: TokenReference) -> UIColor? {
return delegate?.tokenTextViewForegroundColourForTokenRef(self, tokenRef: tokenRef)
}
// MARK: Token text management
fileprivate func effectiveTokenDisplayText(_ originalText: String) -> String {
return tokenTextStorage.effectiveTokenDisplayText(originalText)
}
}
class TokenTextViewControllerInputModeHandler: NSObject, UITextViewDelegate {
fileprivate weak var tokenTextViewController: TokenTextViewController!
init(tokenTextViewController: TokenTextViewController) {
self.tokenTextViewController = tokenTextViewController
}
func textViewDidChangeSelection(_ textView: UITextView) {
if let (_, inputRange) = tokenTextViewController.tokenTextStorage.inputTextAndRange() {
let cursorLocation = textView.selectedRange.location + textView.selectedRange.length
let adjustedLocation = clampCursorLocationToInputRange(cursorLocation, inputRange: inputRange)
if adjustedLocation != cursorLocation || textView.selectedRange.length > 0 {
tokenTextViewController.viewAsTextView.selectedRange = NSRange(location: adjustedLocation, length: 0)
}
} else if let (_, anchorRange) = tokenTextViewController.tokenTextStorage.anchorTextAndRange() {
let adjustedLocation = anchorRange.location + 1
if textView.selectedRange.location != adjustedLocation {
tokenTextViewController.viewAsTextView.selectedRange = NSRange(location: adjustedLocation, length: 0)
}
} else {
_ = tokenTextViewController.resignFirstResponder()
}
}
fileprivate func clampCursorLocationToInputRange(_ cursorLocation: Int, inputRange: NSRange) -> Int {
if cursorLocation < inputRange.location {
return inputRange.location
}
if cursorLocation > inputRange.location + inputRange.length {
return inputRange.location + inputRange.length
}
return cursorLocation
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText newText: String) -> Bool {
if range.length == 0 {
handleInsertion(range, newText: newText)
} else if range.length == 1 && newText.isEmpty {
handleCharacterDeletion(range)
}
return false
}
fileprivate func handleInsertion(_ range: NSRange, newText: String) {
if newText == "\n" {
// Do not insert return, inform delegate
tokenTextViewController.inputDelegate?.tokenTextViewInputTextWasConfirmed(tokenTextViewController)
return
}
// Insert new text with token attribute
let attrString = NSAttributedString(string: newText, attributes: [TokenTextViewControllerConstants.inputTextAttributeName: TokenTextViewControllerConstants.inputTextAttributeTextValue])
tokenTextViewController.viewAsTextView.textStorage.insert(attrString, at: range.location)
tokenTextViewController.viewAsTextView.selectedRange = NSRange(location: range.location + (newText as NSString).length, length: 0)
if let (inputText, _) = tokenTextViewController.tokenTextStorage.inputTextAndRange() {
tokenTextViewController.inputDelegate?.tokenTextViewInputTextDidChange(tokenTextViewController, inputText: inputText)
if let delegate = tokenTextViewController.delegate, delegate.tokenTextViewShouldCancelEditingAtInsert(tokenTextViewController, newText: newText, inputText: inputText) {
tokenTextViewController.cancelEditingAndKeepText()
}
}
}
fileprivate func handleCharacterDeletion(_ range: NSRange) {
if let (_, inputRange) = tokenTextViewController.tokenTextStorage.inputTextAndRange(), let (_, anchorRange) = tokenTextViewController.tokenTextStorage.anchorTextAndRange() {
if range.location >= anchorRange.location && range.location < anchorRange.location + anchorRange.length {
// The anchor ("@") is deleted, input is cancelled
tokenTextViewController.inputDelegate?.tokenTextViewInputTextWasCanceled(tokenTextViewController, reason: .deleteInput)
} else if range.location >= inputRange.location && range.location < inputRange.location + inputRange.length {
// Do deletion
tokenTextViewController.viewAsTextView.textStorage.replaceCharacters(in: range, with: "")
tokenTextViewController.viewAsTextView.selectedRange = NSRange(location: range.location, length: 0)
if let (inputText, _) = tokenTextViewController.tokenTextStorage.inputTextAndRange() {
tokenTextViewController.inputDelegate?.tokenTextViewInputTextDidChange(tokenTextViewController, inputText: inputText)
}
}
} else {
// Input fully deleted, input is cancelled
tokenTextViewController.inputDelegate?.tokenTextViewInputTextWasCanceled(tokenTextViewController, reason: .deleteInput)
}
}
}
extension UITextView {
func characterIndexAtLocation(_ location: CGPoint) -> Int? {
var point = location
point.x -= self.textContainerInset.left
point.y -= self.textContainerInset.top
return self.textContainer.layoutManager?.characterIndex(for: point, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
}
}
extension UITextView {
func textRangeFromNSRange(_ range: NSRange) -> UITextRange? {
let beginning = self.beginningOfDocument
if let start = self.position(from: beginning, offset: range.location),
let end = self.position(from: start, offset: range.length),
let textRange = self.textRange(from: start, to: end) {
return textRange
} else {
return nil
}
}
}
extension TokenTextViewController: PasteMediaTextViewPasteDelegate {
func pasteMediaTextView(_: PasteMediaTextView, shouldAcceptContentOfType type: PasteboardItemType) -> Bool {
return delegate?.tokenTextView(self, shouldAcceptContentOfType: type) ?? false
}
func pasteMediaTextView(_: PasteMediaTextView, didReceive items: [PasteboardItem]) {
delegate?.tokenTextView(self, didReceive: items)
}
}
| true
|
2f5d3bcca2d7a3144b91fefcbb5c20b6bc4f13a0
|
Swift
|
jkb91jkb91/StickyNotes
|
/StickyNotes/Helpers/Constants.swift
|
UTF-8
| 1,125
| 2.828125
| 3
|
[] |
no_license
|
//
// ItemSize.swift
// StickyNotes
//
// Created by XCodeClub on 2019-10-23.
// Copyright © 2019 XCodeClub. All rights reserved.
//
import UIKit
struct Sizes {
static let smallSize = CGSize(width: (UIScreen.main.bounds.width/2) - 10, height: UIScreen.main.bounds.width/2)
static let largeSize = CGSize(width: (UIScreen.main.bounds.width/3) - 10, height: UIScreen.main.bounds.width/3)
}
struct Background {
static let wood = "wood"
static let table = "table"
}
struct Colors {
static let yellow = UIColor(displayP3Red: 255/255, green: 241/255, blue: 113/255, alpha: 1)
static let green = UIColor(displayP3Red: 116/255, green: 242/255, blue: 91/255, alpha: 1)
static let red = UIColor(displayP3Red: 231/255, green: 81/255, blue: 83/255, alpha: 1)
}
struct FontSize {
static let small = 10
static let large = 14
}
struct Titles {
static let small = "small"
static let large = "large"
static let delete = "delete"
static let settings = "settings"
}
struct ColorsToSave {
static let yellow = "yellow"
static let green = "green"
static let red = "red"
}
| true
|
eaa43258d82bec040f2a131a11ae01af19877605
|
Swift
|
GladunVladimir/ios
|
/2019-spring/VladSuhomlinov/FilmWiki-MVC/FilmWiki/Controllers/InfoFilmTableViewController.swift
|
UTF-8
| 3,029
| 2.59375
| 3
|
[] |
no_license
|
//
// InfoFilmTableViewController.swift
// StarWarsWiki
//
// Created by Виталий on 11.03.19.
// Copyright © 2019 vlad. All rights reserved.
//
import UIKit
class InfoFilmTableViewController: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var dateLabel: UILabel!
@IBOutlet private var ratingLabel: UILabel!
@IBOutlet private var descriptionTextView: UITextView!
@IBOutlet private var actorsCollectionView: UICollectionView!
private var actors: [Actor] = []
// swiftlint:disable implicitly_unwrapped_optional
private var film: Film!
// swiftlint:enable implicitly_unwrapped_optional
private var infoFilmService = CreditsServiceNetwork()
override func viewDidLoad() {
super.viewDidLoad()
self.titleLabel.text = film.title
self.dateLabel.text = film.releaseDate
self.ratingLabel.text = "\(film.rating)"
self.descriptionTextView.text = film.description
self.infoFilmService.movieId = film.id
self.actorsCollectionView.delegate = self
self.actorsCollectionView.dataSource = self
loadData()
}
func set(film: Film) {
self.film = film
}
func loadData() {
self.infoFilmService.getData { [unowned self] actors in
self.actors += actors
DispatchQueue.main.async {
self.actorsCollectionView.reloadData()
}
}
}
// MARK: protocol's methods
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 4 {
return self.actorsCollectionView.frame.height + 40
}
return UITableView.automaticDimension
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let destViewController = storyboard.instantiateViewController(withIdentifier: "ActorWebViewController") as? ActorWebViewController else { return }
destViewController.set(actorName: actors[indexPath.row].name)
self.navigationController?.pushViewController(destViewController, animated: true)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.actors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Actor", for: indexPath) as? ActorsCollectionViewCell else {
return collectionView.dequeueReusableCell(withReuseIdentifier: "Actor", for: indexPath)
}
cell.set(actor: actors[indexPath.row])
return cell
}
}
| true
|
e0007dbcd54f29b93dd4ef94943ca2192946363f
|
Swift
|
ReactiveCocoa/ReactiveSwift
|
/Tests/ReactiveSwiftTests/SignalProducerLiftingSpec.swift
|
UTF-8
| 62,380
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// SignalProducerLiftingSpec.swift
// ReactiveSwift
//
// Created by Neil Pankey on 6/14/15.
// Copyright © 2015 GitHub. All rights reserved.
//
import Dispatch
import Foundation
@testable import Nimble
import Quick
@testable import ReactiveSwift
class SignalProducerLiftingSpec: QuickSpec {
override func spec() {
describe("map") {
it("should transform the values of the signal") {
let (producer, observer) = SignalProducer<Int, Never>.pipe()
let mappedProducer = producer.map { String($0 + 1) }
var lastValue: String?
mappedProducer.startWithValues {
lastValue = $0
return
}
expect(lastValue).to(beNil())
observer.send(value: 0)
expect(lastValue) == "1"
observer.send(value: 1)
expect(lastValue) == "2"
}
it("should raplace the values of the signal to constant new value") {
let (producer, observer) = SignalProducer<String, Never>.pipe()
let mappedProducer = producer.map(value: 1)
var lastValue: Int?
mappedProducer.startWithValues {
lastValue = $0
}
expect(lastValue).to(beNil())
observer.send(value: "foo")
expect(lastValue) == 1
observer.send(value: "foobar")
expect(lastValue) == 1
}
}
describe("mapError") {
it("should transform the errors of the signal") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 100, userInfo: nil)
var error: NSError?
producer
.mapError { _ in producerError }
.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.send(error: TestError.default)
expect(error) == producerError
}
}
describe("lazyMap") {
describe("with a scheduled binding") {
var token: Lifetime.Token!
var lifetime: Lifetime!
var destination: [String] = []
var tupleProducer: SignalProducer<(character: String, other: Int), Never>!
var tupleObserver: Signal<(character: String, other: Int), Never>.Observer!
var theLens: SignalProducer<String, Never>!
var getterCounter: Int = 0
var lensScheduler: TestScheduler!
var targetScheduler: TestScheduler!
var target: BindingTarget<String>!
beforeEach {
destination = []
token = Lifetime.Token()
lifetime = Lifetime(token)
let (producer, observer) = SignalProducer<(character: String, other: Int), Never>.pipe()
tupleProducer = producer
tupleObserver = observer
lensScheduler = TestScheduler()
targetScheduler = TestScheduler()
getterCounter = 0
theLens = tupleProducer.lazyMap(on: lensScheduler) { (tuple: (character: String, other: Int)) -> String in
getterCounter += 1
return tuple.character
}
target = BindingTarget<String>(on: targetScheduler, lifetime: lifetime) {
destination.append($0)
}
target <~ theLens
}
it("should not propagate values until scheduled") {
// Send a value along
tupleObserver.send(value: (character: "🎃", other: 42))
// The destination should not change value, and the getter
// should not have evaluated yet, as neither has been scheduled
expect(destination) == []
expect(getterCounter) == 0
// Advance both schedulers
lensScheduler.advance()
targetScheduler.advance()
// The destination receives the previously-sent value, and the
// getter obviously evaluated
expect(destination) == ["🎃"]
expect(getterCounter) == 1
}
it("should evaluate the getter only when scheduled") {
// Send a value along
tupleObserver.send(value: (character: "🎃", other: 42))
// The destination should not change value, and the getter
// should not have evaluated yet, as neither has been scheduled
expect(destination) == []
expect(getterCounter) == 0
// When the getter's scheduler advances, the getter should
// be evaluated, but the destination still shouldn't accept
// the new value
lensScheduler.advance()
expect(getterCounter) == 1
expect(destination) == []
// Sending other values along shouldn't evaluate the getter
tupleObserver.send(value: (character: "😾", other: 42))
tupleObserver.send(value: (character: "🍬", other: 13))
tupleObserver.send(value: (character: "👻", other: 17))
expect(getterCounter) == 1
expect(destination) == []
// Push the scheduler along for the lens, and the getter
// should evaluate
lensScheduler.advance()
expect(getterCounter) == 2
// ...but the destination still won't receive the value
expect(destination) == []
// Finally, pushing the target scheduler along will
// propagate only the first and last values
targetScheduler.advance()
expect(getterCounter) == 2
expect(destination) == ["🎃", "👻"]
}
}
it("should return the result of the getter on each value change") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let scheduler = TestScheduler()
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), Never>.pipe()
let theLens: SignalProducer<String, Never> = tupleProducer.lazyMap(on: scheduler) { $0.character }
var output: [String] = []
theLens.startWithValues { value in
output.append(value)
}
tupleObserver.send(value: initialValue)
scheduler.advance()
expect(output) == ["🎃"]
tupleObserver.send(value: nextValue)
scheduler.advance()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), Never>.pipe()
let scheduler = TestScheduler()
var output: [String] = []
var getterEvaluated = false
let theLens: SignalProducer<String, Never> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in
getterEvaluated = true
return tuple.character
}
// No surprise here, but the getter should not be evaluated
// since the underlying producer has yet to be started.
expect(getterEvaluated).to(beFalse())
// Similarly, sending values won't cause anything to happen.
tupleObserver.send(value: initialValue)
expect(output).to(beEmpty())
expect(getterEvaluated).to(beFalse())
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
// Even when the producer has yet to start, there should be no
// evaluation of the getter
expect(getterEvaluated).to(beFalse())
// Now we send a value through the producer
tupleObserver.send(value: initialValue)
// The getter should still not be evaluated, as it has not yet
// been scheduled
expect(getterEvaluated).to(beFalse())
// Now advance the scheduler to allow things to proceed
scheduler.advance()
// Now the getter gets evaluated, and the output is what we'd
// expect
expect(getterEvaluated).to(beTrue())
expect(output) == ["🎃"]
// And now subsequent values continue to come through
tupleObserver.send(value: nextValue)
scheduler.advance()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily on a different scheduler") {
let initialValue = (character: "🎃", other: 42)
let nextValue = (character: "😾", other: 74)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), Never>.pipe()
let scheduler = TestScheduler()
var output: [String] = []
var getterEvaluated = false
let theLens: SignalProducer<String, Never> = tupleProducer.lazyMap(on: scheduler) { (tuple: (character: String, other: Int)) -> String in
getterEvaluated = true
return tuple.character
}
// No surprise here, but the getter should not be evaluated
// since the underlying producer has yet to be started.
expect(getterEvaluated).to(beFalse())
// Similarly, sending values won't cause anything to happen.
tupleObserver.send(value: initialValue)
expect(output).to(beEmpty())
expect(getterEvaluated).to(beFalse())
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
// Even when the producer has yet to start, there should be no
// evaluation of the getter
expect(getterEvaluated).to(beFalse())
tupleObserver.send(value: initialValue)
// The getter should still not get evaluated, as it was not yet
// scheduled
expect(getterEvaluated).to(beFalse())
expect(output).to(beEmpty())
scheduler.run()
// Now that the scheduler's run, things can continue to move forward
expect(getterEvaluated).to(beTrue())
expect(output) == ["🎃"]
tupleObserver.send(value: nextValue)
// Subsequent values should still be held up by the scheduler
// not getting run
expect(output) == ["🎃"]
scheduler.run()
expect(output) == ["🎃", "😾"]
}
it("should evaluate its getter lazily on the scheduler we specify") {
let initialValue = (character: "🎃", other: 42)
let (tupleProducer, tupleObserver) = SignalProducer<(character: String, other: Int), Never>.pipe()
let labelKey = DispatchSpecificKey<String>()
let testQueue = DispatchQueue(label: "test queue", target: .main)
testQueue.setSpecific(key: labelKey, value: "test queue")
testQueue.suspend()
let testScheduler = QueueScheduler(internalQueue: testQueue)
var output: [String] = []
var isOnTestQueue = false
let theLens = tupleProducer.lazyMap(on: testScheduler) { (tuple: (character: String, other: Int)) -> String in
isOnTestQueue = DispatchQueue.getSpecific(key: labelKey) == "test queue"
return tuple.character
}
// Start the signal, appending future values to the output array
theLens.startWithValues { value in output.append(value) }
testQueue.resume()
expect(isOnTestQueue).to(beFalse())
expect(output).to(beEmpty())
tupleObserver.send(value: initialValue)
expect(isOnTestQueue).toEventually(beTrue())
expect(output).toEventually(equal(["🎃"]))
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "lazyMap") { $0.lazyMap(on: $1) { $0 } }
}
}
describe("filter") {
it("should omit values from the producer") {
let (producer, observer) = SignalProducer<Int, Never>.pipe()
let mappedProducer = producer.filter { $0 % 2 == 0 }
var lastValue: Int?
mappedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 0)
expect(lastValue) == 0
observer.send(value: 1)
expect(lastValue) == 0
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("skipNil") {
it("should forward only non-nil values") {
let (producer, observer) = SignalProducer<Int?, Never>.pipe()
let mappedProducer = producer.skipNil()
var lastValue: Int?
mappedProducer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: nil)
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: nil)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("scan(_:_:)") {
it("should incrementally accumulate a value") {
let (baseProducer, observer) = SignalProducer<String, Never>.pipe()
let producer = baseProducer.scan("", +)
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: "a")
expect(lastValue) == "a"
observer.send(value: "bb")
expect(lastValue) == "abb"
}
}
describe("scan(into:_:)") {
it("should incrementally accumulate a value") {
let (baseProducer, observer) = SignalProducer<String, Never>.pipe()
let producer = baseProducer.scan(into: "") { $0 += $1 }
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: "a")
expect(lastValue) == "a"
observer.send(value: "bb")
expect(lastValue) == "abb"
}
}
describe("scanMap(_:_:)") {
it("should update state and output separately") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.scanMap(false) { state, value -> (Bool, String) in
return (true, state ? "\(value)" : "initial")
}
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == "initial"
observer.send(value: 2)
expect(lastValue) == "2"
observer.send(value: 3)
expect(lastValue) == "3"
}
}
describe("scanMap(into:_:)") {
it("should update state and output separately") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.scanMap(into: false) { (state: inout Bool, value: Int) -> String in
defer { state = true }
return state ? "\(value)" : "initial"
}
var lastValue: String?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == "initial"
observer.send(value: 2)
expect(lastValue) == "2"
observer.send(value: 3)
expect(lastValue) == "3"
}
}
describe("reduce(_:_:)") {
it("should accumulate one value") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.reduce(1, +)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(completed) == true
expect(lastValue) == 4
}
it("should send the initial value if none are received") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.reduce(1, +)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(lastValue) == 1
expect(completed) == true
}
}
describe("reduce(into:_:)") {
it("should accumulate one value") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.reduce(into: 1) { $0 += $1 }
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(completed) == true
expect(lastValue) == 4
}
it("should send the initial value if none are received") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.reduce(into: 1) { $0 += $1 }
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.sendCompleted()
expect(lastValue) == 1
expect(completed) == true
}
}
describe("skip") {
it("should skip initial values") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.skip(first: 1)
var lastValue: Int?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue) == 2
}
it("should not skip any values when 0") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.skip(first: 0)
var lastValue: Int?
producer.startWithValues { lastValue = $0 }
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
}
}
describe("skipRepeats") {
it("should skip duplicate Equatable values") {
let (baseProducer, observer) = SignalProducer<Bool, Never>.pipe()
let producer = baseProducer.skipRepeats()
var values: [Bool] = []
producer.startWithValues { values.append($0) }
expect(values) == []
observer.send(value: true)
expect(values) == [ true ]
observer.send(value: true)
expect(values) == [ true ]
observer.send(value: false)
expect(values) == [ true, false ]
observer.send(value: true)
expect(values) == [ true, false, true ]
}
it("should skip values according to a predicate") {
let (baseProducer, observer) = SignalProducer<String, Never>.pipe()
let producer = baseProducer.skipRepeats { $0.count == $1.count }
var values: [String] = []
producer.startWithValues { values.append($0) }
expect(values) == []
observer.send(value: "a")
expect(values) == [ "a" ]
observer.send(value: "b")
expect(values) == [ "a" ]
observer.send(value: "cc")
expect(values) == [ "a", "cc" ]
observer.send(value: "d")
expect(values) == [ "a", "cc", "d" ]
}
}
describe("skipWhile") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
var lastValue: Int?
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, Never>.pipe()
producer = baseProducer.skip { $0 < 2 }
observer = incomingObserver
lastValue = nil
producer.startWithValues { lastValue = $0 }
}
it("should skip while the predicate is true") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue) == 2
observer.send(value: 0)
expect(lastValue) == 0
}
it("should not skip any values when the predicate starts false") {
expect(lastValue).to(beNil())
observer.send(value: 3)
expect(lastValue) == 3
observer.send(value: 1)
expect(lastValue) == 1
}
}
describe("skipUntil") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
var triggerObserver: Signal<(), Never>.Observer!
var lastValue: Int? = nil
beforeEach {
let (baseProducer, baseIncomingObserver) = SignalProducer<Int, Never>.pipe()
let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), Never>.pipe()
producer = baseProducer.skip(until: triggerProducer)
observer = baseIncomingObserver
triggerObserver = incomingTriggerObserver
lastValue = nil
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .failed, .completed, .interrupted:
break
}
}
}
it("should skip values until the trigger fires") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
triggerObserver.send(value: ())
observer.send(value: 0)
expect(lastValue) == 0
}
it("should skip values until the trigger completes") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue).to(beNil())
observer.send(value: 2)
expect(lastValue).to(beNil())
triggerObserver.sendCompleted()
observer.send(value: 0)
expect(lastValue) == 0
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.skip(until: .init(value: ()))
}
}
describe("take") {
it("should take initial values") {
let (baseProducer, observer) = SignalProducer<Int, Never>.pipe()
let producer = baseProducer.take(first: 2)
var lastValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(lastValue).to(beNil())
expect(completed) == false
observer.send(value: 1)
expect(lastValue) == 1
expect(completed) == false
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == true
}
it("should complete immediately after taking given number of values") {
let numbers = [ 1, 2, 4, 4, 5 ]
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, Never> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
for number in numbers {
observer.send(value: number)
}
}
}
var completed = false
producer
.take(first: numbers.count)
.startWithCompleted { completed = true }
expect(completed) == false
testScheduler.run()
expect(completed) == true
}
it("should interrupt when 0") {
let numbers = [ 1, 2, 4, 4, 5 ]
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, Never> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
for number in numbers {
observer.send(value: number)
}
}
}
var result: [Int] = []
var interrupted = false
producer
.take(first: 0)
.start { event in
switch event {
case let .value(number):
result.append(number)
case .interrupted:
interrupted = true
case .failed, .completed:
break
}
}
expect(interrupted) == true
testScheduler.run()
expect(result).to(beEmpty())
}
}
describe("collect") {
it("should collect all values") {
let (original, observer) = SignalProducer<Int, Never>.pipe()
let producer = original.collect()
let expectedResult = [ 1, 2, 3 ]
var result: [Int]?
producer.startWithValues { value in
expect(result).to(beNil())
result = value
}
for number in expectedResult {
observer.send(value: number)
}
expect(result).to(beNil())
observer.sendCompleted()
expect(result) == expectedResult
}
it("should complete with an empty array if there are no values") {
let (original, observer) = SignalProducer<Int, Never>.pipe()
let producer = original.collect()
var result: [Int]?
producer.startWithValues { result = $0 }
expect(result).to(beNil())
observer.sendCompleted()
expect(result) == []
}
it("should forward errors") {
let (original, observer) = SignalProducer<Int, TestError>.pipe()
let producer = original.collect()
var error: TestError?
producer.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.send(error: .default)
expect(error) == TestError.default
}
it("should collect an exact count of values") {
let (original, observer) = SignalProducer<Int, Never>.pipe()
let producer = original.collect(count: 3)
var observedValues: [[Int]] = []
producer.startWithValues { value in
observedValues.append(value)
}
var expectation: [[Int]] = []
for i in 1...7 {
observer.send(value: i)
if i % 3 == 0 {
expectation.append([Int]((i - 2)...i))
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
} else {
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
}
}
observer.sendCompleted()
expectation.append([7])
expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC()
}
it("should collect values until it matches a certain value") {
let (original, observer) = SignalProducer<Int, Never>.pipe()
let producer = original.collect { _, value in value != 5 }
var expectedValues = [
[5, 5],
[42, 5],
]
producer.startWithValues { value in
expect(value) == expectedValues.removeFirst()
}
producer.startWithCompleted {
expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC()
}
expectedValues
.flatMap { $0 }
.forEach(observer.send(value:))
observer.sendCompleted()
}
it("should collect values until it matches a certain condition on values") {
let (original, observer) = SignalProducer<Int, Never>.pipe()
let producer = original.collect { values in values.reduce(0, +) == 10 }
var expectedValues = [
[1, 2, 3, 4],
[5, 6, 7, 8, 9],
]
producer.startWithValues { value in
expect(value) == expectedValues.removeFirst()
}
producer.startWithCompleted {
expect(expectedValues._bridgeToObjectiveC()) == []._bridgeToObjectiveC()
}
expectedValues
.flatMap { $0 }
.forEach(observer.send(value:))
observer.sendCompleted()
}
}
describe("takeUntil") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
var triggerObserver: Signal<(), Never>.Observer!
var lastValue: Int? = nil
var completed: Bool = false
beforeEach {
let (baseProducer, baseIncomingObserver) = SignalProducer<Int, Never>.pipe()
let (triggerProducer, incomingTriggerObserver) = SignalProducer<(), Never>.pipe()
producer = baseProducer.take(until: triggerProducer)
observer = baseIncomingObserver
triggerObserver = incomingTriggerObserver
lastValue = nil
completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
}
it("should take values until the trigger fires") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == false
triggerObserver.send(value: ())
expect(completed) == true
}
it("should take values until the trigger completes") {
expect(lastValue).to(beNil())
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
expect(completed) == false
triggerObserver.sendCompleted()
expect(completed) == true
}
it("should complete if the trigger fires immediately") {
expect(lastValue).to(beNil())
expect(completed) == false
triggerObserver.send(value: ())
expect(completed) == true
expect(lastValue).to(beNil())
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.take(until: .init(value: ()))
}
}
describe("takeUntilReplacement") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
var replacementObserver: Signal<Int, Never>.Observer!
var lastValue: Int? = nil
var completed: Bool = false
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (replacementProducer, incomingReplacementObserver) = SignalProducer<Int, Never>.pipe()
producer = baseProducer.take(untilReplacement: replacementProducer)
observer = incomingObserver
replacementObserver = incomingReplacementObserver
lastValue = nil
completed = false
producer.start { event in
switch event {
case let .value(value):
lastValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
}
it("should take values from the original then the replacement") {
expect(lastValue).to(beNil())
expect(completed) == false
observer.send(value: 1)
expect(lastValue) == 1
observer.send(value: 2)
expect(lastValue) == 2
replacementObserver.send(value: 3)
expect(lastValue) == 3
expect(completed) == false
observer.send(value: 4)
expect(lastValue) == 3
expect(completed) == false
replacementObserver.send(value: 5)
expect(lastValue) == 5
expect(completed) == false
replacementObserver.sendCompleted()
expect(completed) == true
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.take(untilReplacement: .init(value: 0))
}
}
describe("takeWhile") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, Never>.pipe()
producer = baseProducer.take(while: { $0 <= 4 })
observer = incomingObserver
}
it("should take while the predicate is true") {
var latestValue: Int!
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
for value in -1...4 {
observer.send(value: value)
expect(latestValue) == value
expect(completed) == false
}
observer.send(value: 5)
expect(latestValue) == 4
expect(completed) == true
}
it("should complete if the predicate starts false") {
var latestValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
observer.send(value: 5)
expect(latestValue).to(beNil())
expect(completed) == true
}
}
describe("takeUntil") {
var producer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
beforeEach {
let (baseProducer, incomingObserver) = SignalProducer<Int, Never>.pipe()
producer = baseProducer.take(until: { $0 <= 4 })
observer = incomingObserver
}
it("should take until the predicate is true") {
var latestValue: Int!
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
for value in -1...4 {
observer.send(value: value)
expect(latestValue) == value
expect(completed) == false
}
observer.send(value: 5)
expect(latestValue) == 5
expect(completed) == true
observer.send(value: 6)
expect(latestValue) == 5
}
it("should take and then complete if the predicate starts false") {
var latestValue: Int?
var completed = false
producer.start { event in
switch event {
case let .value(value):
latestValue = value
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
observer.send(value: 5)
expect(latestValue) == 5
expect(completed) == true
}
}
describe("observeOn") {
it("should send events on the given scheduler") {
let testScheduler = TestScheduler()
let (producer, observer) = SignalProducer<Int, Never>.pipe()
var result: [Int] = []
producer
.observe(on: testScheduler)
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
expect(result).to(beEmpty())
testScheduler.run()
expect(result) == [ 1, 2 ]
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "observe(on:)") { $0.observe(on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "observe(on:)") { $0.observe(on: $1) }
}
}
describe("delay") {
it("should send events on the given scheduler after the interval") {
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, Never> = SignalProducer { observer, _ in
testScheduler.schedule {
observer.send(value: 1)
}
testScheduler.schedule(after: .seconds(5)) {
observer.send(value: 2)
observer.sendCompleted()
}
}
var result: [Int] = []
var completed = false
producer
.delay(10, on: testScheduler)
.start { event in
switch event {
case let .value(number):
result.append(number)
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
testScheduler.advance(by: .seconds(4)) // send initial value
expect(result).to(beEmpty())
testScheduler.advance(by: .seconds(10)) // send second value and receive first
expect(result) == [ 1 ]
expect(completed) == false
testScheduler.advance(by: .seconds(10)) // send second value and receive first
expect(result) == [ 1, 2 ]
expect(completed) == true
}
it("should schedule errors immediately") {
let testScheduler = TestScheduler()
let producer: SignalProducer<Int, TestError> = SignalProducer { observer, _ in
// workaround `Class declaration cannot close over value 'observer' defined in outer scope`
let observer = observer
testScheduler.schedule {
observer.send(error: TestError.default)
}
}
var errored = false
producer
.delay(10, on: testScheduler)
.startWithFailed { _ in errored = true }
testScheduler.advance()
expect(errored) == true
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "delay") { $0.delay(10.0, on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "delay") { $0.delay(10.0, on: $1) }
}
}
describe("throttle") {
var scheduler: TestScheduler!
var observer: Signal<Int, Never>.Observer!
var producer: SignalProducer<Int, Never>!
beforeEach {
scheduler = TestScheduler()
let (baseProducer, baseObserver) = SignalProducer<Int, Never>.pipe()
observer = baseObserver
producer = baseProducer.throttle(1, on: scheduler)
}
it("should send values on the given scheduler at no less than the interval") {
var values: [Int] = []
producer.startWithValues { value in
values.append(value)
}
expect(values) == []
observer.send(value: 0)
expect(values) == []
scheduler.advance()
expect(values) == [ 0 ]
observer.send(value: 1)
observer.send(value: 2)
expect(values) == [ 0 ]
scheduler.advance(by: .milliseconds(1500))
expect(values) == [ 0, 2 ]
scheduler.advance(by: .seconds(3))
expect(values) == [ 0, 2 ]
observer.send(value: 3)
expect(values) == [ 0, 2 ]
scheduler.advance()
expect(values) == [ 0, 2, 3 ]
observer.send(value: 4)
observer.send(value: 5)
scheduler.advance()
expect(values) == [ 0, 2, 3 ]
scheduler.rewind(by: .seconds(2))
expect(values) == [ 0, 2, 3 ]
observer.send(value: 6)
scheduler.advance()
expect(values) == [ 0, 2, 3, 6 ]
observer.send(value: 7)
observer.send(value: 8)
scheduler.advance()
expect(values) == [ 0, 2, 3, 6 ]
scheduler.run()
expect(values) == [ 0, 2, 3, 6, 8 ]
}
it("should schedule completion immediately") {
var values: [Int] = []
var completed = false
producer.start { event in
switch event {
case let .value(value):
values.append(value)
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
observer.send(value: 0)
scheduler.advance()
expect(values) == [ 0 ]
observer.send(value: 1)
observer.sendCompleted()
expect(completed) == false
scheduler.run()
expect(values) == [ 0 ]
expect(completed) == true
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "throttle") { $0.throttle(10.0, on: $1) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "throttle") { $0.throttle(10.0, on: $1) }
}
}
describe("debounce") {
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: true) }
}
it("should interrupt ASAP and discard outstanding events") {
testAsyncASAPInterruption(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: false) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: true) }
}
it("should interrupt on the given scheduler") {
testAsyncInterruptionScheduler(op: "debounce") { $0.debounce(10.0, on: $1, discardWhenCompleted: false) }
}
}
describe("sampleWith") {
var sampledProducer: SignalProducer<(Int, String), Never>!
var observer: Signal<Int, Never>.Observer!
var samplerObserver: Signal<String, Never>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (sampler, incomingSamplerObserver) = SignalProducer<String, Never>.pipe()
sampledProducer = producer.sample(with: sampler)
observer = incomingObserver
samplerObserver = incomingSamplerObserver
}
it("should forward the latest value when the sampler fires") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
observer.send(value: 2)
samplerObserver.send(value: "a")
expect(result) == [ "2a" ]
}
it("should do nothing if sampler fires before signal receives value") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
samplerObserver.send(value: "a")
expect(result).to(beEmpty())
}
it("should send lates value multiple times when sampler fires multiple times") {
var result: [String] = []
sampledProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
samplerObserver.send(value: "a")
samplerObserver.send(value: "b")
expect(result) == [ "1a", "1b" ]
}
it("should complete when both inputs have completed") {
var completed = false
sampledProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
samplerObserver.sendCompleted()
expect(completed) == true
}
it("should emit an initial value if the sampler is a synchronous SignalProducer") {
let producer = SignalProducer<Int, Never>([1])
let sampler = SignalProducer<String, Never>(value: "a")
let result = producer.sample(with: sampler)
var valueReceived: String?
result.startWithValues { valueReceived = "\($0.0)\($0.1)" }
expect(valueReceived) == "1a"
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.sample(with: .init(value: 0))
}
}
describe("sampleOn") {
var sampledProducer: SignalProducer<Int, Never>!
var observer: Signal<Int, Never>.Observer!
var samplerObserver: Signal<(), Never>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (sampler, incomingSamplerObserver) = SignalProducer<(), Never>.pipe()
sampledProducer = producer.sample(on: sampler)
observer = incomingObserver
samplerObserver = incomingSamplerObserver
}
it("should forward the latest value when the sampler fires") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
samplerObserver.send(value: ())
expect(result) == [ 2 ]
}
it("should do nothing if sampler fires before signal receives value") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
samplerObserver.send(value: ())
expect(result).to(beEmpty())
}
it("should send lates value multiple times when sampler fires multiple times") {
var result: [Int] = []
sampledProducer.startWithValues { result.append($0) }
observer.send(value: 1)
samplerObserver.send(value: ())
samplerObserver.send(value: ())
expect(result) == [ 1, 1 ]
}
it("should complete when both inputs have completed") {
var completed = false
sampledProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
samplerObserver.sendCompleted()
expect(completed) == true
}
it("should emit an initial value if the sampler is a synchronous SignalProducer") {
let producer = SignalProducer<Int, Never>([1])
let sampler = SignalProducer<(), Never>(value: ())
let result = producer.sample(on: sampler)
var valueReceived: Int?
result.startWithValues { valueReceived = $0 }
expect(valueReceived) == 1
}
describe("memory") {
class Payload {
let action: () -> Void
init(onDeinit action: @escaping () -> Void) {
self.action = action
}
deinit {
action()
}
}
var sampledProducer: SignalProducer<Payload, Never>!
var samplerObserver: Signal<(), Never>.Observer!
var observer: Signal<Payload, Never>.Observer!
// Mitigate the "was written to, but never read" warning.
_ = samplerObserver
beforeEach {
let (producer, incomingObserver) = SignalProducer<Payload, Never>.pipe()
let (sampler, _samplerObserver) = Signal<(), Never>.pipe()
sampledProducer = producer.sample(on: sampler)
samplerObserver = _samplerObserver
observer = incomingObserver
}
it("should free payload when interrupted after complete of incoming producer") {
var payloadFreed = false
let disposable = sampledProducer.start()
observer.send(value: Payload { payloadFreed = true })
observer.sendCompleted()
expect(payloadFreed) == false
disposable.dispose()
expect(payloadFreed) == true
}
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.sample(on: .init(value: ()))
}
}
describe("withLatest(from: signal)") {
var withLatestProducer: SignalProducer<(Int, String), Never>!
var observer: Signal<Int, Never>.Observer!
var sampleeObserver: Signal<String, Never>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (samplee, incomingSampleeObserver) = Signal<String, Never>.pipe()
withLatestProducer = producer.withLatest(from: samplee)
observer = incomingObserver
sampleeObserver = incomingSampleeObserver
}
it("should forward the latest value when the receiver fires") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
sampleeObserver.send(value: "b")
observer.send(value: 1)
expect(result) == [ "1b" ]
}
it("should do nothing if receiver fires before samplee sends value") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
expect(result).to(beEmpty())
}
it("should send latest value with samplee value multiple times when receiver fires multiple times") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
observer.send(value: 1)
observer.send(value: 2)
expect(result) == [ "1a", "2a" ]
}
it("should complete when receiver has completed") {
var completed = false
withLatestProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == true
}
it("should not affect when samplee has completed") {
var event: Signal<(Int, String), Never>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendCompleted()
expect(event).to(beNil())
}
it("should not affect when samplee has interrupted") {
var event: Signal<(Int, String), Never>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendInterrupted()
expect(event).to(beNil())
}
}
describe("withLatest(from: producer)") {
var withLatestProducer: SignalProducer<(Int, String), Never>!
var observer: Signal<Int, Never>.Observer!
var sampleeObserver: Signal<String, Never>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (samplee, incomingSampleeObserver) = SignalProducer<String, Never>.pipe()
withLatestProducer = producer.withLatest(from: samplee)
observer = incomingObserver
sampleeObserver = incomingSampleeObserver
}
it("should forward the latest value when the receiver fires") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
sampleeObserver.send(value: "b")
observer.send(value: 1)
expect(result) == [ "1b" ]
}
it("should do nothing if receiver fires before samplee sends value") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
observer.send(value: 1)
expect(result).to(beEmpty())
}
it("should send latest value with samplee value multiple times when receiver fires multiple times") {
var result: [String] = []
withLatestProducer.startWithValues { result.append("\($0.0)\($0.1)") }
sampleeObserver.send(value: "a")
observer.send(value: 1)
observer.send(value: 2)
expect(result) == [ "1a", "2a" ]
}
it("should complete when receiver has completed") {
var completed = false
withLatestProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == true
}
it("should not affect when samplee has completed") {
var event: Signal<(Int, String), Never>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendCompleted()
expect(event).to(beNil())
}
it("should not affect when samplee has interrupted") {
var event: Signal<(Int, String), Never>.Event? = nil
withLatestProducer.start { event = $0 }
sampleeObserver.sendInterrupted()
expect(event).to(beNil())
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.withLatest(from: .init(value: 0))
}
}
describe("combineLatestWith") {
var combinedProducer: SignalProducer<(Int, Double), Never>!
var observer: Signal<Int, Never>.Observer!
var otherObserver: Signal<Double, Never>.Observer!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, Never>.pipe()
let (otherSignal, incomingOtherObserver) = SignalProducer<Double, Never>.pipe()
combinedProducer = producer.combineLatest(with: otherSignal)
observer = incomingObserver
otherObserver = incomingOtherObserver
}
it("should forward the latest values from both inputs") {
var latest: (Int, Double)?
combinedProducer.startWithValues { latest = $0 }
observer.send(value: 1)
expect(latest).to(beNil())
// is there a better way to test tuples?
otherObserver.send(value: 1.5)
expect(latest?.0) == 1
expect(latest?.1) == 1.5
observer.send(value: 2)
expect(latest?.0) == 2
expect(latest?.1) == 1.5
}
it("should complete when both inputs have completed") {
var completed = false
combinedProducer.startWithCompleted { completed = true }
observer.sendCompleted()
expect(completed) == false
otherObserver.sendCompleted()
expect(completed) == true
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.combineLatest(with: .init(value: 0))
}
}
describe("zipWith") {
var leftObserver: Signal<Int, Never>.Observer!
var rightObserver: Signal<String, Never>.Observer!
var zipped: SignalProducer<(Int, String), Never>!
beforeEach {
let (leftProducer, incomingLeftObserver) = SignalProducer<Int, Never>.pipe()
let (rightProducer, incomingRightObserver) = SignalProducer<String, Never>.pipe()
leftObserver = incomingLeftObserver
rightObserver = incomingRightObserver
zipped = leftProducer.zip(with: rightProducer)
}
it("should combine pairs") {
var result: [String] = []
zipped.startWithValues { result.append("\($0.0)\($0.1)") }
leftObserver.send(value: 1)
leftObserver.send(value: 2)
expect(result) == []
rightObserver.send(value: "foo")
expect(result) == [ "1foo" ]
leftObserver.send(value: 3)
rightObserver.send(value: "bar")
expect(result) == [ "1foo", "2bar" ]
rightObserver.send(value: "buzz")
expect(result) == [ "1foo", "2bar", "3buzz" ]
rightObserver.send(value: "fuzz")
expect(result) == [ "1foo", "2bar", "3buzz" ]
leftObserver.send(value: 4)
expect(result) == [ "1foo", "2bar", "3buzz", "4fuzz" ]
}
it("should complete when the shorter signal has completed") {
var result: [String] = []
var completed = false
zipped.start { event in
switch event {
case let .value((left, right)):
result.append("\(left)\(right)")
case .completed:
completed = true
case .failed, .interrupted:
break
}
}
expect(completed) == false
leftObserver.send(value: 0)
leftObserver.sendCompleted()
expect(completed) == false
expect(result) == []
rightObserver.send(value: "foo")
expect(completed) == true
expect(result) == [ "0foo" ]
}
it("should be able to fallback to SignalProducer for contextual lookups") {
_ = SignalProducer<Int, Never>.empty
.zip(with: .init(value: 0))
}
}
describe("materialize") {
it("should reify events from the signal") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
var latestEvent: Signal<Int, TestError>.Event?
producer
.materialize()
.startWithValues { latestEvent = $0 }
observer.send(value: 2)
expect(latestEvent).toNot(beNil())
if let latestEvent = latestEvent {
switch latestEvent {
case let .value(value):
expect(value) == 2
case .failed, .completed, .interrupted:
fail()
}
}
observer.send(error: TestError.default)
if let latestEvent = latestEvent {
switch latestEvent {
case .failed:
break
case .value, .completed, .interrupted:
fail()
}
}
}
}
describe("dematerialize") {
typealias IntEvent = Signal<Int, TestError>.Event
var observer: Signal<IntEvent, Never>.Observer!
var dematerialized: SignalProducer<Int, TestError>!
beforeEach {
let (producer, incomingObserver) = SignalProducer<IntEvent, Never>.pipe()
observer = incomingObserver
dematerialized = producer.dematerialize()
}
it("should send values for Value events") {
var result: [Int] = []
dematerialized
.assumeNoErrors()
.startWithValues { result.append($0) }
expect(result).to(beEmpty())
observer.send(value: .value(2))
expect(result) == [ 2 ]
observer.send(value: .value(4))
expect(result) == [ 2, 4 ]
}
it("should error out for Error events") {
var errored = false
dematerialized.startWithFailed { _ in errored = true }
expect(errored) == false
observer.send(value: .failed(TestError.default))
expect(errored) == true
}
it("should complete early for Completed events") {
var completed = false
dematerialized.startWithCompleted { completed = true }
expect(completed) == false
observer.send(value: IntEvent.completed)
expect(completed) == true
}
}
describe("materializeResults") {
it("should reify results from the signal") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
var latestResult: Result<Int, TestError>?
producer
.materializeResults()
.startWithValues { latestResult = $0 }
observer.send(value: 2)
expect(latestResult).toNot(beNil())
if let latestResult = latestResult {
switch latestResult {
case .success(let value):
expect(value) == 2
case .failure:
fail()
}
}
observer.send(error: TestError.default)
if let latestResult = latestResult {
switch latestResult {
case .failure(let error):
expect(error) == TestError.default
case .success:
fail()
}
}
}
}
describe("dematerializeResults") {
typealias IntResult = Result<Int, TestError>
var observer: Signal<IntResult, Never>.Observer!
var dematerialized: SignalProducer<Int, TestError>!
beforeEach {
let (producer, incomingObserver) = SignalProducer<IntResult, Never>.pipe()
observer = incomingObserver
dematerialized = producer.dematerializeResults()
}
it("should send values for Value results") {
var result: [Int] = []
dematerialized
.assumeNoErrors()
.startWithValues { result.append($0) }
expect(result).to(beEmpty())
observer.send(value: .success(2))
expect(result) == [ 2 ]
observer.send(value: .success(4))
expect(result) == [ 2, 4 ]
}
it("should error out for Error results") {
var errored = false
dematerialized.startWithFailed { _ in errored = true }
expect(errored) == false
observer.send(value: .failure(TestError.default))
expect(errored) == true
}
}
describe("takeLast") {
var observer: Signal<Int, TestError>.Observer!
var lastThree: SignalProducer<Int, TestError>!
beforeEach {
let (producer, incomingObserver) = SignalProducer<Int, TestError>.pipe()
observer = incomingObserver
lastThree = producer.take(last: 3)
}
it("should send the last N values upon completion") {
var result: [Int] = []
lastThree
.assumeNoErrors()
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
expect(result).to(beEmpty())
observer.sendCompleted()
expect(result) == [ 2, 3, 4 ]
}
it("should send less than N values if not enough were received") {
var result: [Int] = []
lastThree
.assumeNoErrors()
.startWithValues { result.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.sendCompleted()
expect(result) == [ 1, 2 ]
}
it("should send nothing when errors") {
var result: [Int] = []
var errored = false
lastThree.start { event in
switch event {
case let .value(value):
result.append(value)
case .failed:
errored = true
case .completed, .interrupted:
break
}
}
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
expect(errored) == false
observer.send(error: TestError.default)
expect(errored) == true
expect(result).to(beEmpty())
}
}
describe("timeoutWithError") {
var testScheduler: TestScheduler!
var producer: SignalProducer<Int, TestError>!
var observer: Signal<Int, TestError>.Observer!
beforeEach {
testScheduler = TestScheduler()
let (baseProducer, incomingObserver) = SignalProducer<Int, TestError>.pipe()
producer = baseProducer.timeout(after: 2, raising: TestError.default, on: testScheduler)
observer = incomingObserver
}
it("should complete if within the interval") {
var completed = false
var errored = false
producer.start { event in
switch event {
case .completed:
completed = true
case .failed:
errored = true
case .value, .interrupted:
break
}
}
testScheduler.schedule(after: .seconds(1)) {
observer.sendCompleted()
}
expect(completed) == false
expect(errored) == false
testScheduler.run()
expect(completed) == true
expect(errored) == false
}
it("should error if not completed before the interval has elapsed") {
var completed = false
var errored = false
producer.start { event in
switch event {
case .completed:
completed = true
case .failed:
errored = true
case .value, .interrupted:
break
}
}
testScheduler.schedule(after: .seconds(3)) {
observer.sendCompleted()
}
expect(completed) == false
expect(errored) == false
testScheduler.run()
expect(completed) == false
expect(errored) == true
}
it("should be available for Never") {
let producer: SignalProducer<Int, TestError> = SignalProducer<Int, Never>.never
.timeout(after: 2, raising: TestError.default, on: testScheduler)
_ = producer
}
}
describe("attempt") {
it("should forward original values upon success") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attempt { _ in
return .success(())
}
var current: Int?
producer
.assumeNoErrors()
.startWithValues { value in
current = value
}
for value in 1...5 {
observer.send(value: value)
expect(current) == value
}
}
it("should error if an attempt fails") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attempt { _ in
return .failure(.default)
}
var error: TestError?
producer.startWithFailed { err in
error = err
}
observer.send(value: 42)
expect(error) == TestError.default
}
}
describe("attemptMap") {
it("should forward mapped values upon success") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attemptMap { num -> Result<Bool, TestError> in
return .success(num % 2 == 0)
}
var even: Bool?
producer
.assumeNoErrors()
.startWithValues { value in
even = value
}
observer.send(value: 1)
expect(even) == false
observer.send(value: 2)
expect(even) == true
}
it("should error if a mapping fails") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
let producer = baseProducer.attemptMap { _ -> Result<Bool, TestError> in
return .failure(.default)
}
var error: TestError?
producer.startWithFailed { err in
error = err
}
observer.send(value: 42)
expect(error) == TestError.default
}
}
describe("combinePrevious") {
var observer: Signal<Int, Never>.Observer!
let initialValue: Int = 0
var latestValues: (Int, Int)?
beforeEach {
latestValues = nil
let (signal, baseObserver) = SignalProducer<Int, Never>.pipe()
observer = baseObserver
signal.combinePrevious(initialValue).startWithValues { latestValues = $0 }
}
it("should forward the latest value with previous value") {
expect(latestValues).to(beNil())
observer.send(value: 1)
expect(latestValues?.0) == initialValue
expect(latestValues?.1) == 1
observer.send(value: 2)
expect(latestValues?.0) == 1
expect(latestValues?.1) == 2
}
}
}
}
private func testAsyncInterruptionScheduler(
op: String,
file: FileString = #file,
line: UInt = #line,
transform: (SignalProducer<Int, Never>, TestScheduler) -> SignalProducer<Int, Never>
) {
var isInterrupted = false
let scheduler = TestScheduler()
let producer = transform(SignalProducer(0 ..< 128), scheduler)
let failedExpectations = gatherFailingExpectations {
let disposable = producer.startWithInterrupted { isInterrupted = true }
expect(isInterrupted) == false
disposable.dispose()
expect(isInterrupted) == false
scheduler.run()
expect(isInterrupted) == true
}
if !failedExpectations.isEmpty {
fail("The async operator `\(op)` does not interrupt on the appropriate scheduler.",
location: SourceLocation(file: file, line: line))
}
}
private func testAsyncASAPInterruption(
op: String,
file: FileString = #file,
line: UInt = #line,
transform: (SignalProducer<Int, Never>, TestScheduler) -> SignalProducer<Int, Never>
) {
var valueCount = 0
var interruptCount = 0
var unexpectedEventCount = 0
let scheduler = TestScheduler()
let disposable = transform(SignalProducer(0 ..< 128), scheduler)
.start { event in
switch event {
case .value:
valueCount += 1
case .interrupted:
interruptCount += 1
case .failed, .completed:
unexpectedEventCount += 1
}
}
expect(interruptCount) == 0
expect(unexpectedEventCount) == 0
expect(valueCount) == 0
disposable.dispose()
scheduler.run()
let failedExpectations = gatherFailingExpectations {
expect(interruptCount) == 1
expect(unexpectedEventCount) == 0
expect(valueCount) == 0
}
if !failedExpectations.isEmpty {
fail("The ASAP interruption test of the async operator `\(op)` has failed.",
location: SourceLocation(file: file, line: line))
}
}
| true
|
3b240091b3e7bfd6d7b03a7a390b2117d9b0f680
|
Swift
|
leiguang/ViewController
|
/ViewController/Photos Browser/PhotosBrowserViewController.swift
|
UTF-8
| 7,575
| 2.90625
| 3
|
[] |
no_license
|
//
// PhotosBrowserViewController.swift
// ViewController
//
// Created by 雷广 on 2018/5/21.
// Copyright © 2018年 leiguang. All rights reserved.
//
// [UIScrollView Tutorial](https://www.raywenderlich.com/159481/uiscrollview-tutorial-getting-started)
// [ImageScrollView](https://github.com/imanoupetit/ImageScrollView)
// [Zooming by Tapping](https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/UIScrollView_pg/ZoomingByTouch/ZoomingByTouch.html#//apple_ref/doc/uid/TP40008179-CH4-SW1)
// [Zooming Programmatically](https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/UIScrollView_pg/ZoomZoom/ZoomZoom.html#//apple_ref/doc/uid/TP40008179-CH102-SW7)
/**
Displaying a Page Control Indicator
For the final part of this UIScrollView tutorial, you will add a UIPageControl to your application.
Fortunately, UIPageViewController has the ability to automatically provide a UIPageControl.
To do so, your UIPageViewController must have a transition style of UIPageViewControllerTransitionStyleScroll, and you must provide implementations of two special methods on UIPageViewControllerDataSource. You previously set the Transition Style- great job!- so all you need to do is add these two methods inside the UIPageViewControllerDataSource extension on ManagePageViewController:
*/
import UIKit
final class PhotosBrowserViewController: UIPageViewController {
var photos: [String] = []
/// present时的index (即显示第几张图)
var presentIndex: Int = 0
var transitioning = PhotosBrowserTransition()
/// 从上一页面的view弹出的views数组,分别与其photoIndex对应
var fromViewArray: [UIView]?
/// 用于状态栏显示/隐藏 避免底层的viewController present时状态栏突变
var isViewDidAppear: Bool = false
/// - Paramaters:
/// - photos: Array of photo urls.
/// - presentIndex: The index of present, default value is 0.
/// - fromViewArray: The array contains view from which PhotosBrowserViewController presented transition.
init(photos: [String], presentIndex: Int = 0, fromViewArray: [UIView]? = nil) {
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey: 8.0])
self.photos = photos
self.presentIndex = presentIndex
self.fromViewArray = fromViewArray
self.modalPresentationStyle = .overFullScreen
self.modalPresentationCapturesStatusBarAppearance = true
self.transitioningDelegate = transitioning
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0, alpha: 0.9)
dataSource = self
let viewController = zoomedPhotoController(index: presentIndex)
let viewControllers = [viewController]
setViewControllers(viewControllers,
direction: .forward,
animated: false,
completion: nil)
// Customize the colors of the UIPageControl.
let pageControl = UIPageControl.appearance()
pageControl.pageIndicatorTintColor = .lightGray
pageControl.currentPageIndicatorTintColor = .red
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewDidAppear = true
setNeedsStatusBarAppearanceUpdate()
}
deinit {
print("\(self) deinit")
}
override var prefersStatusBarHidden: Bool {
return isViewDidAppear ? true : false
}
private func zoomedPhotoController(index: Int) -> PhotoZoomedViewController {
return PhotoZoomedViewController(photoIndex: index, photoName: photos[index], placeholderPhotoName: nil)
}
}
extension PhotosBrowserViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? PhotoZoomedViewController,
let index = viewController.photoIndex, index > photos.startIndex
{
return zoomedPhotoController(index: index - 1)
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let viewController = viewController as? PhotoZoomedViewController,
let index = viewController.photoIndex, index < photos.endIndex - 1
{
return zoomedPhotoController(index: index + 1)
}
return nil
}
// MARK: - UIPageControl
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return photos.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return presentIndex
}
}
// MARK: - 用于present/dismiss时图片的过渡效果
extension PhotosBrowserViewController {
/// 当前index
/// (本以为没法实现currentIndex,经测试 还是能给它加上,因为初始状态或每次切换后 self.viewControllers.count都为1,毕竟若不能实现currentIndex,即无法实现图片的转换过渡,在本需求中就得放弃使用UIPageController做了,有点叼)
var currentIndex: Int {
if let zoomedPhotoVC = viewControllers?.first as? PhotoZoomedViewController,
let index = photos.index(of: zoomedPhotoVC.photoName) {
return index
}
return 0
}
/// present开始时,tempImageView的frame
var imageStartFrameOfPresent: CGRect? {
guard let fromViewArray = fromViewArray, currentIndex >= 0, currentIndex < fromViewArray.endIndex else { return nil }
let v = fromViewArray[currentIndex]
let rect = v.convert(v.bounds, to: nil)
return rect
}
/// dismiss完成时,tempImageView的frame
var imageEndFrameOfDismiss: CGRect? {
guard let fromViewArray = fromViewArray, currentIndex >= 0, currentIndex < fromViewArray.endIndex else { return nil }
let v = fromViewArray[currentIndex]
let rect = v.convert(v.bounds, to: nil)
return rect
}
/// present完成时,imageView的frame
var imageEndFrameOfPresent: CGRect? {
if let zoomedPhotoVC = viewControllers?.first as? PhotoZoomedViewController
{
return zoomedPhotoVC.imageEndFrameOfPresent
}
return nil
}
/// dismiss开始时,imageView的frame
var imageStartFrameOfDismiss: CGRect? {
if let zoomedPhotoVC = viewControllers?.first as? PhotoZoomedViewController
{
return zoomedPhotoVC.imageStartFrameOfDismiss
}
return nil
}
/// present时的image
var imageOfPresent: UIImage? {
if let zoomedPhotoVC = viewControllers?.first as? PhotoZoomedViewController
{
return zoomedPhotoVC.initializedPhoto
}
return nil
}
/// present时的imageView
var currentImageView: UIImageView? {
if let zoomedPhotoVC = viewControllers?.first as? PhotoZoomedViewController
{
return zoomedPhotoVC.imageView
}
return nil
}
}
| true
|
ae2334891dbae19649a6f9e55619b21e85326042
|
Swift
|
thanhtamle/attendance-ios
|
/Attendance/Attendance/Views/ItemIntroView.swift
|
UTF-8
| 4,283
| 2.625
| 3
|
[] |
no_license
|
//
// ItemIntroView.swift
// Attendance
//
// Created by Thanh-Tam Le on 7/13/17.
// Copyright © 2017 citynow. All rights reserved.
//
import UIKit
class ItemIntroView: UIView {
var iconImgView = UIImageView()
var titleLabel = UILabel()
var descriptionLabel = UILabel()
var signInButton = UIButton()
var signUpButton = UIButton()
var constraintsAdded = false
convenience init() {
self.init(frame: .zero)
iconImgView.contentMode = .scaleAspectFit
iconImgView.clipsToBounds = true
titleLabel.font = UIFont(name: "OpenSans-bold", size: 17)
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.white
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.numberOfLines = 0
descriptionLabel.font = UIFont(name: "OpenSans", size: 16)
descriptionLabel.textAlignment = .center
descriptionLabel.textColor = UIColor.white
descriptionLabel.lineBreakMode = .byWordWrapping
descriptionLabel.numberOfLines = 0
signInButton.setTitle("LOGIN", for: .normal)
signInButton.backgroundColor = UIColor.white
signInButton.setTitleColor(Global.colorMain, for: .normal)
signInButton.setTitleColor(Global.colorSelected, for: .highlighted)
signInButton.layer.cornerRadius = 5
signInButton.titleLabel?.font = UIFont(name: "OpenSans-semibold", size: 15)
signInButton.clipsToBounds = true
signUpButton.setTitle("SIGNUP", for: .normal)
signUpButton.backgroundColor = UIColor.white
signUpButton.setTitleColor(Global.colorMain, for: .normal)
signUpButton.setTitleColor(Global.colorSelected, for: .highlighted)
signUpButton.layer.cornerRadius = 5
signUpButton.titleLabel?.font = UIFont(name: "OpenSans-semibold", size: 15)
signUpButton.clipsToBounds = true
addSubview(iconImgView)
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(signInButton)
addSubview(signUpButton)
setNeedsUpdateConstraints()
}
override func updateConstraints() {
super.updateConstraints()
if !constraintsAdded {
constraintsAdded = true
var buttonSize: CGFloat = 40
var alpha: CGFloat = 40
var imgHeight: CGFloat = 200
var imgWidth: CGFloat = 270
var imgTop: CGFloat = 100
var alphaButton: CGFloat = 15
var distanceButton: CGFloat = 40
if DeviceType.IS_IPAD {
buttonSize = 50
alpha = 150
imgHeight = 300
imgWidth = 400
imgTop = 150
alphaButton = 40
distanceButton = 60
}
iconImgView.autoPinEdge(toSuperviewEdge: .top, withInset: imgTop)
iconImgView.autoSetDimensions(to: CGSize(width: imgWidth, height: imgHeight))
iconImgView.autoAlignAxis(toSuperviewAxis: .vertical)
titleLabel.autoPinEdge(.top, to: .bottom, of: iconImgView, withOffset: 10)
titleLabel.autoPinEdge(toSuperviewEdge: .left, withInset: alpha)
titleLabel.autoPinEdge(toSuperviewEdge: .right, withInset: alpha)
descriptionLabel.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: 10)
descriptionLabel.autoPinEdge(toSuperviewEdge: .left, withInset: alpha)
descriptionLabel.autoPinEdge(toSuperviewEdge: .right, withInset: alpha)
signUpButton.autoPinEdge(toSuperviewEdge: .left, withInset: alphaButton)
signUpButton.autoPinEdge(toSuperviewEdge: .bottom, withInset: 70)
signUpButton.autoMatch(.width, to: .width, of: signInButton)
signUpButton.autoSetDimension(.height, toSize: buttonSize)
signInButton.autoPinEdge(toSuperviewEdge: .right, withInset: alphaButton)
signInButton.autoMatch(.width, to: .width, of: signUpButton)
signInButton.autoPinEdge(.left, to: .right, of: signUpButton, withOffset: distanceButton)
signInButton.autoPinEdge(.bottom, to: .bottom, of: signUpButton)
signInButton.autoMatch(.height, to: .height, of: signUpButton)
}
}
}
| true
|
79ba9b44463236f208eb26e5000bcb19fb14821a
|
Swift
|
jeewanct/ReusableFramework
|
/ReusableFramework/PopUp/CustomPopup.swift
|
UTF-8
| 2,791
| 2.640625
| 3
|
[] |
no_license
|
//
// CustomPopup.swift
// ReusableFramework
//
// Created by JEEVAN TIWARI on 09/01/19.
// Copyright © 2019 AccountingApp. All rights reserved.
//
import UIKit
open class CustomPopup: UIView{
public override init(frame: CGRect) {
super.init(frame: frame)
addViews()
backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.6602662852)
}
func addViews(){
addSubview(cardView)
cardView.addSubview(searchBar)
cardView.addSubview(tableView)
cardView.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
cardView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -32).isActive = true
cardView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.9).isActive = true
cardView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.6).isActive = true
searchBar.topAnchor.constraint(equalTo: cardView.topAnchor, constant: 8).isActive = true
searchBar.leftAnchor.constraint(equalTo: cardView.leftAnchor, constant: 8).isActive = true
searchBar.rightAnchor.constraint(equalTo: cardView.rightAnchor, constant: -8).isActive = true
tableView.topAnchor.constraint(equalTo: searchBar.bottomAnchor, constant: 0).isActive = true
tableView.leftAnchor.constraint(equalTo: cardView.leftAnchor, constant: 8).isActive = true
tableView.rightAnchor.constraint(equalTo: cardView.rightAnchor, constant: -8).isActive = true
tableView.bottomAnchor.constraint(equalTo: cardView.bottomAnchor, constant: -8).isActive = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.showsHorizontalScrollIndicator = false
tableView.separatorStyle = .none
return tableView
}()
lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.placeholder = "Search"
searchBar.isTranslucent = true
searchBar.searchBarStyle = .minimal
searchBar.tintColor = #colorLiteral(red: 0.4470588235, green: 0.568627451, blue: 0.9568627451, alpha: 1)
return searchBar
}()
lazy var cardView: CardView = {
let cardView = CardView()
cardView.translatesAutoresizingMaskIntoConstraints = false
cardView.cornerRadius = 10
cardView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
return cardView
}()
}
| true
|
81e0f4b3c2e860e645b224bf27a293af3ec9075c
|
Swift
|
tonyoditanto/oalaa
|
/Oalaa/Task/TaskVC.swift
|
UTF-8
| 2,743
| 2.6875
| 3
|
[] |
no_license
|
//
// TaskVC.swift
// Oalaa
//
// Created by Steven Wijaya on 20/05/20.
// Copyright © 2020 M2-911. All rights reserved.
//
import UIKit
class TaskVC: UIViewController {
@IBOutlet weak var dailyCV: UICollectionView!
@IBOutlet weak var achievementCV: UICollectionView!
var dailies = [DailyMission]()
var achievements = [Achievement]()
override func viewDidLoad() {
super.viewDidLoad()
initDelegate()
dailies = TaskManager.getAllDailyMissions()
achievements = TaskManager.getAllAchievement()
navigationController?.setNavigationBarHidden(true, animated: false)
}
func initDelegate() {
dailyCV.delegate = self
dailyCV.dataSource = self
achievementCV.delegate = self
achievementCV.dataSource = self
}
@IBAction func didTapCloseButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
extension TaskVC: UICollectionViewDelegate, UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.achievementCV {
return achievements.count
} else {
return dailies.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.achievementCV {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AchievementCell", for: indexPath) as! AchievementCell
let achievement = achievements[indexPath.row]
cell.nameLabel.text = achievement.name
cell.actionLabel.text = achievement.actionName
cell.badgeIV.image = UIImage(systemName: achievement.image)
let defaults = UserDefaults.standard
let v = defaults.integer(forKey: achievement.userDefaultKey)
cell.valuePV.progress = Float(v) / Float(achievement.maxValue)
cell.valueLabel.text = (v > achievement.maxValue) ? "Completed" : "\(v) / \(achievement.maxValue)"
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DailyCell", for: indexPath) as! DailyCell
let daily = dailies[indexPath.row]
cell.nameLabel.text = daily.name
cell.imageIV.image = UIImage(systemName: daily.image)
cell.valuePV.progress = Float(daily.value) / Float(daily.maxValue)
cell.valueLabel.text = (daily.value > daily.maxValue) ? "\(daily.maxValue) / \(daily.maxValue)" : "\(daily.value) / \(daily.maxValue)"
return cell
}
}
}
| true
|
d3c2975ca6c425a2bcb23cfdab5941178994e6e3
|
Swift
|
andriitishchenko/DownloadManager
|
/OPF/Extentions.swift
|
UTF-8
| 701
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// Extentions.swift
// OPF
//
// Created by Andrii Tishchenko on 01.09.15.
// Copyright (c) 2015 Andrii Tishchenko. All rights reserved.
//
import Cocoa
extension Double {
var bit: Double { return self * 8.0 }
var Byte: Double { return self}
var kB: Double { return self / 1024.0 }
var MB: Double { return self / 1024.0 / 1024.0}
var GB: Double { return self / 1024.0 / 1024.0 / 1024.0 }
var TB: Double { return self / 1024.0 / 1024.0 / 1024.0 / 1024.0 }
}
extension Double {
var km: Double { return self * 1000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1000.0 }
var ft: Double { return self / 3.28084 }
}
| true
|
80be7202e60ea7355afc2b5e72b10d544cf960e7
|
Swift
|
NikolaiBorisov/Determinant
|
/Determinant/Controller/WelcomeVC/View/WelcomeViewMaker.swift
|
UTF-8
| 2,069
| 2.640625
| 3
|
[] |
no_license
|
//
// WelcomeViewMaker.swift
// Determinant
//
// Created by NIKOLAI BORISOV on 24.07.2021.
//
import UIKit
final class WelcomeViewMaker {
unowned var container: WelcomeViewController
init(container: WelcomeViewController) {
self.container = container
}
lazy var welcomeLabel: UILabel = {
let label = DeterminantLabel(type: .welcomeVCLabel)
label.text = NSLocalizedString("Welcome to the Game\n«Determinant»", comment: "Label")
return label
}()
lazy var instructionButton: UIButton = {
let button = DeterminantButton(type: .instruction)
button.setTitle(NSLocalizedString("Read the Instruction", comment: "Button"), for: .normal)
return button
}()
lazy var gameButton: UIButton = {
let button = DeterminantButton(type: .game)
button.backgroundColor = .systemIndigo
button.setTitle(NSLocalizedString("Game", comment: "Button"), for: .normal)
return button
}()
lazy var gifImageViewContainer: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.loadGif(name: Constants.Gif.name)
return imageView
}()
func setupLayouts() {
[
welcomeLabel,
instructionButton,
gifImageViewContainer,
gameButton
]
.forEach { container.view.addSubview($0) }
welcomeLabel.snp.makeConstraints {
$0.top.equalTo(container.view.safeAreaLayoutGuide.snp.top).offset(10.0)
$0.centerX.equalToSuperview()
}
instructionButton.snp.makeConstraints {
$0.centerX.centerY.equalToSuperview()
$0.leading.equalToSuperview().offset(20.0)
}
gameButton.snp.makeConstraints {
$0.bottom.equalTo(container.view.safeAreaLayoutGuide.snp.bottom).offset(-10.0)
$0.leading.equalToSuperview().offset(20.0)
$0.trailing.equalToSuperview().offset(-20.0)
}
gifImageViewContainer.snp.makeConstraints {
$0.bottom.equalTo(gameButton.snp.top).offset(-10.0)
$0.centerX.equalToSuperview()
}
}
}
| true
|
fd41499906d0ddb7dc42905ce6ebdc743d092b34
|
Swift
|
FrankWuoO/Snake
|
/Snake/Model/Snake.swift
|
UTF-8
| 1,700
| 3.53125
| 4
|
[] |
no_license
|
//
// Snake.swift
// Snake
//
// Created by cheng-en wu on 4/17/20.
// Copyright © 2020 Frank. All rights reserved.
//
import UIKit
class Snake: SnakeAbility, SnakeAction{
var gameBounds: GameBounds
var body: [Point] = []
var direction: Direction = .right
required init(bounds: GameBounds = .default, length: Int = 2) {
self.gameBounds = bounds
for i in 0..<length{
body.append(Point(x: i, y: 0))
}
}
func grow() {
let nextPoint = trail
body.insert(nextPoint, at: 0)
}
func canMove(to point: Point) -> Result<Void, MovementError> {
guard point.x >= 0, point.y >= 0 else {
return .failure(.collideBounds)
}
guard point.x < gameBounds.width, point.y < gameBounds.height else {
return .failure(.collideBounds)
}
guard !body.contains(point) else {
return .failure(.biteItself)
}
return .success(())
}
func move(_ toDirection: Direction? = nil) -> Result<Void, MovementError>{
var toDirection: Direction = toDirection ?? self.direction
//如果是相反,則將前進方向改為現在方向
if direction.isOpposite(with: toDirection) {
toDirection = self.direction
}
let nextPoint = head.move(toDirection)
let result = canMove(to: nextPoint)
switch result {
case .success:
body.removeFirst()
body.append(nextPoint)
self.direction = toDirection
case .failure(let error):
print(error)
}
return result
}
}
| true
|
2155da2bcb5560bc0c1a9d97a7c7f98bc52d126a
|
Swift
|
EzhovAndrei/instaStuff
|
/InstaStuff/InstaStuff/Classes/Managers/TemplatesStorage/DataToCoreData.swift
|
UTF-8
| 4,564
| 2.703125
| 3
|
[] |
no_license
|
//
// DataToCoreData.swift
// InstaStuff
//
// Created by aezhov on 05/08/2019.
// Copyright © 2019 Андрей Ежов. All rights reserved.
//
import UIKit
import CoreData
extension TemplatesStorage {
func dataToPhotoFrameInTemplate(itemId: Int, centerX: CGFloat, centerY: CGFloat, angle: CGFloat, widthScale: CGFloat, applyScale: Bool = true, photoName: String?, context: NSManagedObjectContext) -> CDPhotoFrameInTemplate {
let frameInTemplate = CDPhotoFrameInTemplate(context: context)
frameInTemplate.photoName = photoName
frameInTemplate.itemId = Int64(itemId)
let settings = generateSettings(centerX: centerX, centerY: centerY, angle: angle, widthScale: widthScale, applyScale: applyScale, context: context)
frameInTemplate.settings = settings
return frameInTemplate
}
func photoFrame(itemId: Int, ratio: CGFloat, frameName: String?, isShape: Bool, context: NSManagedObjectContext) -> CDPhotoFrameItem {
let photoFrame = CDPhotoFrameItem(context: context)
photoFrame.frameImageName = frameName
photoFrame.ratio = Float(ratio)
photoFrame.id = Int64(itemId)
photoFrame.isShape = isShape
return photoFrame
}
func photoFrameSettings(centerX: CGFloat, centerY: CGFloat, angle: CGFloat, widthScale: CGFloat, ratio: CGFloat, round: CGFloat, context: NSManagedObjectContext) -> CDPhotoFrameSettings {
let photoFrameSettings = CDPhotoFrameSettings(context: context)
photoFrameSettings.midX = Float(centerX)
photoFrameSettings.midY = Float(centerY)
photoFrameSettings.angle = Float(angle)
photoFrameSettings.width = Float(widthScale)
photoFrameSettings.ratio = Float(ratio)
photoFrameSettings.round = Float(round)
return photoFrameSettings
}
func dataToTextItemInTemplate(ratio: CGFloat, centerX: CGFloat, centerY: CGFloat, angle: CGFloat, widthScale: CGFloat, applyScale: Bool = true, text: String? = nil, context: NSManagedObjectContext) -> CDTextItemInTemplate {
let textInTemplate = CDTextItemInTemplate(context: context)
textInTemplate.ratio = Float(ratio)
let settings = generateSettings(centerX: centerX, centerY: centerY, angle: angle, widthScale: widthScale, applyScale: applyScale, context: context)
textInTemplate.settings = settings
return textInTemplate
}
func generateSettings(centerX: CGFloat, centerY: CGFloat, angle: CGFloat, widthScale: CGFloat, applyScale: Bool = true, context: NSManagedObjectContext) -> CDItemSettings {
let settings = CDItemSettings(context: context)
settings.midX = Float(centerX / (applyScale ? 108.0 : 1))
settings.midY = Float(centerY / (applyScale ? 192.0 : 1))
settings.angle = Float(angle)
settings.widthScale = Float(widthScale / (applyScale ? 108.0 : 1))
return settings
}
func defaultTextSettings(context: NSManagedObjectContext) -> CDTextSettings {
return textSettings(aligment: .center, color: .black, backgroundColor: .clear, fontSize: 40, kern: 1, lineSpacing: 1, fontName: .cheque, text: "Type your text", context: context)
}
func textSettings(aligment: Aligment, color: UIColor, backgroundColor: UIColor, fontSize: CGFloat, kern: CGFloat, lineSpacing: CGFloat, fontName: FontEnum, text: String, context: NSManagedObjectContext) -> CDTextSettings {
let textSettings = CDTextSettings(context: context)
textSettings.aligment = Int64(aligment.rawValue)
textSettings.backgroundColor = backgroundColor
textSettings.color = color
textSettings.fontSize = Float(fontSize)
textSettings.kern = Float(kern)
textSettings.lineSpacing = Float(lineSpacing)
textSettings.fontName = fontName.rawValue
textSettings.text = text
return textSettings
}
func stuffInTemplate(itemId: Int, centerX: CGFloat, centerY: CGFloat, angle: CGFloat, widthScale: CGFloat, applyScale: Bool = true, context: NSManagedObjectContext) -> CDStuffItemInTemplate {
let stuffInTemplate = CDStuffItemInTemplate(context: context)
stuffInTemplate.itemId = Int64(itemId)
let settings = generateSettings(centerX: centerX, centerY: centerY, angle: angle, widthScale: widthScale, applyScale: applyScale, context: context)
stuffInTemplate.settings = settings
return stuffInTemplate
}
}
| true
|
835d8a511d81994cf5149baf7c01d144cc07e2d8
|
Swift
|
gatlin-carrier/haushalt
|
/Haushalt/Model/Chore.swift
|
UTF-8
| 782
| 2.703125
| 3
|
[] |
no_license
|
//
// Chore.swift
// Haushalt
//
// Created by Gatlin Carrier on 12/23/18.
// Copyright © 2018 Gatlin Carrier. All rights reserved.
//
import Foundation
class Chore {
private(set) var username: String!
private(set) var choreText: String!
private(set) var dueDate: String!
private(set) var deleted: Bool!
private(set) var documentId: String!
private(set) var doer: String!
private(set) var group: Bool!
init(username: String, choreText: String, dueDate: String, deleted: Bool, documentId: String, doer: String, group: Bool) {
self.username = username
self.choreText = choreText
self.dueDate = dueDate
self.deleted = deleted
self.documentId = documentId
self.doer = doer
self.group = group
}
}
| true
|
e4fd0c6fc250f6d72fb3d103dafaa582a7bf7226
|
Swift
|
MrShuJi/two
|
/two/webViewController.swift
|
UTF-8
| 1,425
| 2.671875
| 3
|
[] |
no_license
|
//
// webViewController.swift
// two
//
// Created by shuji on 2017/10/16.
// Copyright © 2017年 shuji. All rights reserved.
//
import UIKit
class webViewController: UIViewController, UIWebViewDelegate {
var detailURL = "http://www.baidu.com"
var webViews: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webViews = UIWebView()
self.pleaseWait()
webViews.frame = view.bounds
let url = NSURL(string: detailURL);
// let request = NSURLRequest(url: url as! URL);
webViews.loadHTMLString(detailURL, baseURL: nil)
webViews.scalesPageToFit = true
self.webViews.delegate = self
// Do any additional setup after loading the view.
view.addSubview(webViews)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//webView代理方法,网页内容加载完成时调用
func webViewDidFinishLoad(_ webView:UIWebView){
self.clearAllNotice()
}
//webView代理方法,链接地址发生改变的时候调用
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
return true
}
}
| true
|
7e9bc79bfd0f26a236e907a41f374b78a7b93284
|
Swift
|
tinhpv/swiftui-netflix-ui-clone
|
/Netflix Rebuild/Extensions/String+Ext.swift
|
UTF-8
| 327
| 2.59375
| 3
|
[] |
no_license
|
//
// String+Ext.swift
// Netflix Rebuild
//
// Created by TinhPV on 8/5/21.
//
import UIKit
extension String {
func widthOfString(font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
}
| true
|
1198f8af9728c32c9e4a39e93ce2158f93ce1311
|
Swift
|
naruthk/mobile-uw-food-app
|
/UW Food App/Controller/MainViewController.swift
|
UTF-8
| 1,074
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// MainViewController.swift
// UW Food App
//
// Created by Thipok Cholsaipant on 8/7/20.
// Copyright © 2020 iSchool. All rights reserved.
//
import FluentIcons
import UIKit
private enum TabTitles: String, CustomStringConvertible {
case Discover
case Search
case Account
var description: String {
return self.rawValue
}
}
private var tabIcons = [
TabTitles.Discover: UIImage(fluent: .compassNorthwest28Regular),
TabTitles.Search: UIImage(fluent: .search28Regular),
TabTitles.Account: UIImage(fluent: .person28Regular)
]
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
if let vcs = viewControllers {
for vc in vcs {
let item = vc.tabBarItem as UITabBarItem
if let title = item.title,
let tab = TabTitles(rawValue: title),
let image = tabIcons[tab] {
item.title = title
item.image = image
}
}
}
}
}
| true
|
b30de45709fdc21f6c3754888aa9f3d87e89b839
|
Swift
|
bunoza/task-CardsGame
|
/task-CardsGame/Game/CardsGame.swift
|
UTF-8
| 891
| 3.421875
| 3
|
[] |
no_license
|
//
// CardsGame.swift
// task-CardsGame
//
// Created by Domagoj Bunoza on 05.08.2021..
//
import Foundation
class CardsGame {
var sequence : [Int]
var deckCompletedAfter : Int
init(userInput: String) {
var sequence = [Int](repeating: 0, count: 52)
var deckCompletedAfter : Int = 0
for i in 1...Int(userInput)! {
let temp = Int.random(in: 0 ..< 52)
sequence[temp] += 1
if !sequence.contains(0) && deckCompletedAfter == 0 {
deckCompletedAfter = i
}
}
// print(sequence)
// print(deckCompletedAfter)
self.sequence = sequence
self.deckCompletedAfter = deckCompletedAfter
}
func getSequence() -> [Int] {
return sequence
}
func getDeckCompletedAfter() -> Int {
return deckCompletedAfter
}
}
| true
|
dcff5ce36bad3b1c4b9ce97abc1232c1e44dca73
|
Swift
|
zxmmxzzxmmxz/PartsCollector
|
/PartsCollector/TypeCollector.swift
|
UTF-8
| 411
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// TypeCollector.swift
// PartsCollector
//
// Created by ximinz on 2016-04-25.
// Copyright © 2016 ximinz. All rights reserved.
//
import Foundation
class TypeCollector{
var types:[String]!
init(types:[String]){
self.types = types
}
func add_a_type(type:String){
types.append(type)
}
func get_types()->[String]{
return types
}
}
| true
|
9fda025e8c5705128e2fc89a662586f2d271d585
|
Swift
|
PauloFavero/Swift-LearningProjects
|
/Swift - Playgrounds/Swift - Estruturas Básicas.playground/Pages/Comandos de Condição 3.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,267
| 4.71875
| 5
|
[] |
no_license
|
//: [Anterior](@previous)
//: # Estruturas Básicas
//:
//: ## Comandos de Condição
import Foundation
let x = 1
//:O outro comando de condição disponível é o *switch-case*
switch x {
//: - Cada *case* pode tratar um único valor:
case 1:
print("Valor é 1")
//: - Um conjunto finito de valores separado por vírgulas:
case 3,5:
print("Valor é 3 ou 5")
//: - Uma faixa de valores (o que é definido por ...):
case 8...15:
print("Valor está entre 8 e 15")
//: - Uma faixa de valores aberta (definido por ..<):
case 16..<20:
print("Valor está entre 16 e 19")
//: - Note: O comando switch deve ser exaustivo. Sendo assim, caso
//: nem todos os valores possíveis sejam tratados em uma cláusula
//: é necessário incluir uma cláusula *default* para tratar todos
//: os valores não cobertos:
default:
print("Outro valor")
}
//: Swift permite tratar strings e enumerações (que serão vistas posteriormente) em cláusulas *switch-case*:
let comando = "F"
switch comando {
case "F":
print("Andando para frente...")
case "T":
print("Andando para trás...")
case "D":
print("Virando a direita...")
case "E":
print("Virando a esquerda...")
default:
print("Comando inválido!")
}
//: [Próximo](@next)
| true
|
4d7b830b47eb5308ecf07658f51af6f2c342faef
|
Swift
|
Thienle149/StudentIOS
|
/AppMusic/AppMusic/Views/Cells/RecentlyAddedCollectionViewCell.swift
|
UTF-8
| 1,034
| 2.59375
| 3
|
[] |
no_license
|
//
// RecentlyAddedCollectionViewCell.swift
// AppMusic
//
// Created by thienle on 3/21/20.
// Copyright © 2020 thienle. All rights reserved.
//
import Foundation
import UIKit
class RecentlyAddedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var backgroundImage: CustomImageView!
@IBOutlet weak var song: UILabel!
@IBOutlet weak var singer: UILabel!
static let identifier: String = "RecentlyAddedCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setUp(_ model: MediaModel) {
print("\(NetworkServices.hostname)/\(model.path!))")
let size = CGSize(width: 200, height: 200)
self.backgroundImage.loadImage(with: "\(NetworkServices.hostname)/\(model.path!)/\(UtilityFunc.formatImageOnURL(format: "jpeg", width: Int(size.width), height: Int(size.height)))", identifier: "\(model._id!)recent", type: .server, size: CGSize(width: size.width, height: size.height))
self.song.text = model.name
self.singer.text = model.author
}
}
| true
|
b9a642756850fb44208787641d7cb6b5c6a2a427
|
Swift
|
djkhz/AppExtensionsDemo
|
/SegmentedToday/View Models/DoneViewModel.swift
|
UTF-8
| 615
| 2.6875
| 3
|
[] |
no_license
|
//
// DoneViewModel.swift
// AppExtensionsDemo
//
// Created by Vesza Jozsef on 12/06/15.
// Copyright (c) 2015 József Vesza. All rights reserved.
//
import UIKit
import TodoKit
struct DoneViewModel: TodoViewModelType, DataProviderType {
let store: ShoppingStoreType
var items: [ShoppingItem] {
return store.items().filter { $0.status != false }
}
init(store: ShoppingStoreType = ShoppingItemStore()) {
self.store = store
}
func dataForRow(row: Int) -> TodoCellDataType {
return TodayCellData(title: titleForRow(row), checked: statusForRow(row))
}
}
| true
|
4e7878672168b720a8617de5311cca0ac13138a3
|
Swift
|
AZbang/vingoapp
|
/Vingo/ContentView.swift
|
UTF-8
| 741
| 2.609375
| 3
|
[] |
no_license
|
//
// ContentView.swift
// HelloWorld
//
// Created by Andrey Zhevlakov on 17.07.2020.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var app: AppStore
var body: some View {
ZStack {
NavigationView {
MainView().environmentObject(self.app).background(BackgroundParalax())
}.zIndex(1)
VStack {
if self.app.storyMode {
Story()
.environmentObject(self.app)
.transition(AnyTransition.move(edge: .bottom))
}
}.zIndex(2)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
84b8afb10c4b3212e9279d492da22d41893a7d1d
|
Swift
|
wahello/Recap
|
/Recap/AddressProvider.swift
|
UTF-8
| 1,722
| 2.921875
| 3
|
[] |
no_license
|
//
// AddressProvider.swift
// MeMailer5000
//
// Created by Alex Brashear on 1/31/17.
// Copyright © 2017 memailer. All rights reserved.
//
import Foundation
typealias AddressVerificationCompletion = (_ address: Address?, _ error: AddressError?) -> Void
class AddressProvider {
private let parser = AddressParser()
private let verifyURLString = "https://api.lob.com/v1/us_verifications"
private let networkClient = NetworkClient()
func verify(address: Address, completion: @escaping AddressVerificationCompletion) {
verify(name: address.name, line1: address.primaryLine, line2: address.secondaryLine, city: address.city, state: address.state, zip: address.zip, completion: completion)
}
func verify(name: String, line1: String, line2: String, city: String, state: String, zip: String, completion: @escaping AddressVerificationCompletion) {
guard let url = URL(string: verifyURLString) else { return completion(nil, .unknownFailure) }
let data = formatHTTPBody(withLine1: line1, line2: line2, city: city, state: state, zip: zip)
networkClient.POST(url: url, data: data) { [weak self] json in
guard let json = json else { return completion(nil, .unknownFailure) }
let (address, error) = self?.parser.parse(json: json, name: name) ?? (nil, .unknownFailure)
DispatchQueue.main.async {
completion(address, error)
}
}
}
private func formatHTTPBody(withLine1 line1: String, line2: String, city: String, state: String, zip: String) -> Data? {
return "primary_line=\(line1)&secondary_line=\(line2)&city=\(city)&state=\(state)&zip_code=\(zip)".data(using: .utf8)
}
}
| true
|
b3380cdd372a5344c147aaefe459eaf63580f9eb
|
Swift
|
helloabbin/Wia
|
/Wia/WColor.swift
|
UTF-8
| 1,951
| 2.8125
| 3
|
[] |
no_license
|
//
// WColor.swift
// Wia
//
// Created by Abbin Varghese on 31/12/16.
// Copyright © 2016 Abbin Varghese. All rights reserved.
//
import UIKit
class WColor: UIColor {
override open class var green: UIColor {
get {
return UIColor.init(red: 76/255, green: 175/255, blue: 80/255, alpha: 1)
}
}
override open class var red: UIColor {
get {
return UIColor.init(red: 244/255, green: 67/255, blue: 54/255, alpha: 1)
}
}
open class var mainColor: UIColor {
get {
return UIColor.init(red: 255/255, green: 171/255, blue: 0/255, alpha: 1)
}
}
open class func colorFor(value : CGFloat) -> UIColor {
if value > 9 {
return UIColor.init(red: 42/255, green: 82/255, blue: 6/255, alpha: 1.0)
}
else if value > 8 {
return UIColor.init(red: 55/255, green: 115/255, blue: 1/255, alpha: 1.0)
}
else if value > 7 {
return UIColor.init(red: 81/255, green: 158/255, blue: 37/255, alpha: 1.0)
}
else if value > 6 {
return UIColor.init(red: 143/255, green: 197/255, blue: 44/255, alpha: 1.0)
}
else if value > 5 {
return UIColor.init(red: 198/255, green: 208/255, blue: 21/255, alpha: 1.0)
}
else if value > 4 {
return UIColor.init(red: 255/255, green: 208/255, blue: 5/255, alpha: 1.0)
}
else if value > 3 {
return UIColor.init(red: 255/255, green: 177/255, blue: 5/255, alpha: 1.0)
}
else if value > 2 {
return UIColor.init(red: 255/255, green: 108/255, blue: 3/255, alpha: 1.0)
}
else if value > 1 {
return UIColor.init(red: 217/255, green: 27/255, blue: 17/255, alpha: 1.0)
}
else {
return UIColor.init(red: 198/255, green: 26/255, blue: 34/255, alpha: 1.0)
}
}
}
| true
|
f70876d17a36f25a806df45c3db7d4c12783eaf0
|
Swift
|
dhythm/caloriedonate
|
/caloriedonate/logViewController.swift
|
UTF-8
| 4,623
| 2.59375
| 3
|
[] |
no_license
|
import Foundation
import UIKit
import CoreData
import Charts
import SwiftyJSON
class logViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var chartView: LineChartView!
// Height of StatusBar
let sbHeight: CGFloat = UIApplication.shared.statusBarFrame.height
// Height of ChartView
let cHeight: CGFloat = 200
var days = [String]()
var weight = [Double]()
init() {
super.init(nibName: nil, bundle: nil)
//self.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 3)
self.tabBarItem = UITabBarItem(title: "Weight", image: #imageLiteral(resourceName: "icons8-accounting-60"), tag: 3)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
// setting for background
let bgColor: UIColor = UIColor.init(red: 245/255.0, green: 245/255.0, blue: 245/255.0, alpha: 1.0)
self.view.backgroundColor = bgColor
/*
chartView = LineChartView(frame: CGRect(x: 0, y: sbHeight, width: UIScreen.main.bounds.width, height: cHeight))
self.view.addSubview(chartView)
*/
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// fetch record
let viewContext = self.appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<WeightData> = WeightData.fetchRequest()
do {
days.removeAll()
weight.removeAll()
let results = try viewContext.fetch(fetchRequest)
for i in 0 ..< results.count {
let df = DateFormatter()
df.dateFormat = "MM/dd"
//days.append(df.string(from: results[i].date! as Date))
weight.append(Double(results[i].weight))
}
} catch {
fatalError("Failed to fetch data: \(error)")
}
/*
//
chartView.backgroundColor = UIColor.white
if weight.count > 0 {
chartView.leftAxis.axisMinimum = weight.min()! * 0.85
chartView.leftAxis.axisMaximum = weight.max()! * 1.15
}
//
chartView.legend.enabled = false
chartView.pinchZoomEnabled = false
chartView.doubleTapToZoomEnabled = false
chartView.dragEnabled = false
chartView.drawBordersEnabled = true
//
//chartView.leftAxis.drawLabelsEnabled = false
chartView.rightAxis.drawLabelsEnabled = false
//chartView.leftAxis.drawGridLinesEnabled = false
chartView.rightAxis.drawGridLinesEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
chartView.xAxis.labelPosition = .bottom
// title of graph
chartView.chartDescription?.text = ""
// padding of graph
chartView.extraTopOffset = 0.0
chartView.extraRightOffset = 20.0
chartView.extraBottomOffset = 10.0
chartView.extraLeftOffset = 0.0
// set values to x-axis
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: days)
chartView.xAxis.granularity = 1
// set values to y-axis
var entries: [ChartDataEntry] = []
for (i, d) in weight.enumerated() {
entries.append(ChartDataEntry(x: Double(i), y: d))
}
let dataset = LineChartDataSet(values: entries, label: "Data")
// hide the values over points
dataset.drawValuesEnabled = false
dataset.drawCircleHoleEnabled = false
dataset.circleColors = [UIColor.black]
dataset.circleRadius = 4.0
dataset.colors = [UIColor.black]
chartView.data = LineChartData(dataSet: dataset)
*/
/*
// create record
for i in 1 ..< 6 {
let newRecord = NSManagedObject(entity: weightdata!, insertInto: viewContext)
newRecord.setValue(Date(timeInterval: 86400 * Double(i), since: Date()), forKey: "date")
newRecord.setValue(70.1, forKey: "weight")
do {
try viewContext.save()
} catch {
//
}
}
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
aef802c129d5b5e769d56dee7f7eb26380f3ecf2
|
Swift
|
Ashish-US/CommitsApp
|
/CommitsApp/Commits/CommitCell.swift
|
UTF-8
| 2,621
| 2.671875
| 3
|
[] |
no_license
|
//
// CommitCell.swift
// CommitsApp
//
// Created by Ashish Singh on 9/26/21.
//
import UIKit
class CommitCell: UITableViewCell {
var message: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textColor = .systemGreen
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var author: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textColor = .systemBlue
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var hashLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textColor = .darkGray
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let seperatorView: UIView = {
let view = UIView()
view.backgroundColor = .darkGray
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var vStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [message, author, hashLabel, seperatorView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .equalCentering
stackView.alignment = .leading
stackView.spacing = 2
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpCell()
}
override func prepareForReuse() {
super.prepareForReuse()
configure(loading: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(loading: Bool) {
}
func setUpCell() {
let marginGuide = contentView.layoutMarginsGuide
// add album name
contentView.addSubview(vStackView)
setupStackConstraints()
}
func setupStackConstraints() {
[vStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
vStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10),
vStackView.heightAnchor.constraint(equalTo: contentView.heightAnchor, constant: 5),
vStackView.widthAnchor.constraint(equalTo: contentView.widthAnchor, constant: -5)].forEach {
$0.isActive = true
}
seperatorView.heightAnchor.constraint(equalToConstant: 4).isActive = true
}
}
| true
|
df01227c21b88deec0afb78c69ddfcb572786ee8
|
Swift
|
qianshijia/CodingTest
|
/TinyWeatherTests/TinyWeatherTests.swift
|
UTF-8
| 1,390
| 2.84375
| 3
|
[] |
no_license
|
//
// TinyWeatherTests.swift
// TinyWeatherTests
//
// Created by Shijia Qian on 26/11/2015.
// Copyright © 2015 Eric Qian. All rights reserved.
//
import XCTest
class TinyWeatherTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAPIRequest() {
let mocLat = "-33.0", mocLong = "150.0"
let request = WeatherAPIRequest(lat: mocLat, long: mocLong)
let expectation = "/forecast/b34898f66f4edd80f7b91fbd41d457e4/-33.0,150.0"
XCTAssert(request.APIPath == expectation)
}
func testWeatherModel() {
let mocJSONResponse = ["currently": [
"summary": "MockSummary",
"temperature": NSNumber(float: 75.0)
]]
let model = CurrentWeatherInfoModel(responseData: mocJSONResponse)
XCTAssert(model.summary == "MockSummary");
XCTAssert(model.temperatureFahrenheit == "75.0")
let temperatureCelsius = (75.0 - 32) / 1.8
XCTAssert(model.temperatureCelsius == String(format: "%.1f", temperatureCelsius))
}
}
| true
|
33283919704ddecff058d3034d340b62e421e2b6
|
Swift
|
EvilPluto/Secret-Contacts
|
/Secret Contacts/WelcomeViewController.swift
|
UTF-8
| 4,038
| 2.609375
| 3
|
[] |
no_license
|
//
// WelcomeViewController.swift
// Secret Contacts
//
// Created by mac on 16/12/18.
// Copyright © 2016年 pluto. All rights reserved.
//
import UIKit
/**
欢迎界面,首次开启应用时加载
---
**Parameters**
* scrollView: 界面里用来滑动的View
* pageControl: 界面的选择按钮,分别对应每个分页
* btn: 用来点击开始的按钮
*/
class WelcomeViewController: UIViewController, UIScrollViewDelegate {
private var scrollView: UIScrollView = UIScrollView()
private var pageControl: UIPageControl = UIPageControl()
private let colorArray: [UIColor] = [.green, .yellow, .black, .red]
private let btn: UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// TODO: 初始化scrollView
scrollView.frame = self.view.bounds
scrollView.contentSize = CGSize(width: self.view.frame.width * 4, height: self.view.frame.height)
scrollView.isPagingEnabled = true // 保证页式滑动
scrollView.bounces = false // 禁止弹性
scrollView.showsHorizontalScrollIndicator = false // 禁止出现滑动条
scrollView.delegate = self
self.view.addSubview(self.scrollView)
for index in 0 ..< 4 {
let imageView = UIImageView(frame:
CGRect(
x: CGFloat(index) * self.view.frame.width,
y: 0,
width: self.view.frame.width,
height: self.view.frame.height
))
imageView.backgroundColor = self.colorArray[index]
scrollView.addSubview(imageView)
}
// TODO: 初始化PageControl
pageControl.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height - 30)
pageControl.currentPageIndicatorTintColor = .blue
pageControl.pageIndicatorTintColor = .white
pageControl.numberOfPages = 4
pageControl.addTarget(self, action: #selector(self.scrollViewDidEndDecelerating(_:)), for: .valueChanged)
self.view.addSubview(self.pageControl)
// TODO: 初始化btn
self.btn.frame =
CGRect(
x: self.view.frame.width * 3,
y: self.view.frame.height,
width: self.view.frame.width,
height: 50
)
self.btn.setTitle("进入通讯录", for: .normal)
self.btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
self.btn.setTitleColor(UIColor.gray, for: .highlighted)
self.btn.backgroundColor = .orange
self.btn.alpha = 0
self.btn.addTarget(self, action: #selector(self.toMainView(_:)), for: .touchUpInside)
self.scrollView.addSubview(self.btn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndex: Int = Int(scrollView.contentOffset.x / self.view.frame.width)
pageControl.currentPage = currentIndex
if currentIndex == 3 {
UIView.animate(
withDuration: 0.5,
delay: 0,
options: .curveEaseInOut,
animations: {
self.btn.alpha = 1.0
self.btn.layer.setAffineTransform(CGAffineTransform(translationX: 0, y: -100))
},
completion: { (_) -> Void in
}
)
} else {
UIView.animate(withDuration: 0, animations: {
self.btn.layer.setAffineTransform(CGAffineTransform.identity)
self.btn.alpha = 0
})
}
}
func toMainView(_ sender: Any?) {
let welcomeView = UIStoryboard(name: "Main", bundle: nil)
let rootView = welcomeView.instantiateViewController(withIdentifier: "Root")
self.present(rootView, animated: true, completion: nil)
}
}
| true
|
13b0db8c36324ae75442701d21bac6f381efd7e1
|
Swift
|
JuanjoDBZ/ShipAndBox
|
/ShipAndBox/ShipAndBox/SABRegister/RegisterNewUser/ExternalDataManager/ExternalDataManager.swift
|
UTF-8
| 3,748
| 2.84375
| 3
|
[] |
no_license
|
//
// ExternalDataManager.swift
// ShipAndBox
//
// Created by Juan Esquivel on 06/07/21.
//
import Foundation
import UIKit
class ExternalDataManager: NSObject, URLSessionDelegate {
public func autenticar<T: Decodable>(with documents: [String:String], objectType: T.Type, completion: @escaping (EnumsRequestAndErrors.Result<T>) -> Void) {
guard let ineFront = documents["IneFront"] else { return }
guard let ineBack = documents["IneBack"] else { return }
guard let faceCustomer = documents["FaceCustomer"] else { return }
let parameters = [
"IneBack": ineBack,
"FaceCustomer": faceCustomer,
"IneFront": ineFront
]
//create the url with URL
let url = URL(string: "https://ec2-3-136-112-167.us-east-2.compute.amazonaws.com:4443/Api/validateDocument")!
//create the session object
let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(EnumsRequestAndErrors.Result.failure(EnumsRequestAndErrors.APPError.networkError(error!)))
return
}
guard let data = data else {
completion(EnumsRequestAndErrors.Result.failure(EnumsRequestAndErrors.APPError.dataNotFound))
return
}
do {
//create decodable object from data
let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
completion(EnumsRequestAndErrors.Result.success(decodedObject))
} catch let error {
completion(EnumsRequestAndErrors.Result.failure(EnumsRequestAndErrors.APPError.jsonParsingError(error as! DecodingError)))
}
})
task.resume()
}
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard challenge.previousFailureCount == 0 else {
challenge.sender?.cancel(challenge)
// Inform the user that the user name and password are incorrect
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// Within your authentication handler delegate method, you should check to see if the challenge protection space has an authentication type of NSURLAuthenticationMethodServerTrust
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
// and if so, obtain the serverTrust information from that protection space.
&& challenge.protectionSpace.serverTrust != nil
&& challenge.protectionSpace.host == "ec2-3-136-112-167.us-east-2.compute.amazonaws.com" {
let proposedCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, proposedCredential)
}
}
}
| true
|
5090024944328ab8720e2c4fb53bbe9f67e82ceb
|
Swift
|
mpclarkson/StravaSwift
|
/Sources/StravaSwift/Club.swift
|
UTF-8
| 1,564
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
//
// Club.swift
// StravaSwift
//
// Created by Matthew on 11/11/2015.
// Copyright © 2015 Matthew Clarkson. All rights reserved.
//
import Foundation
import SwiftyJSON
/**
Clubs represent groups of athletes on Strava. They can be public or private. The object is returned in summary or detailed representations.
**/
public final class Club: Strava {
public let id: Int?
public let profileMedium: URL?
public let profile: URL?
public let name: String?
public let description: String?
public let city: String?
public let state: String?
public let country: String?
public let clubType: ClubType?
public let sportType: SportType?
public let isPrivate: Bool?
public let memberCount: Int?
public let resourceState: ResourceState?
/**
Initializer
- Parameter json: SwiftyJSON object
- Internal
**/
required public init(_ json: JSON) {
id = json["id"].int
name = json["name"].string
description = json["description"].string
resourceState = json["resource_state"].strava(ResourceState.self)
city = json["city"].string
state = json["state"].string
country = json["country"].string
clubType = json["club_type"].strava(ClubType.self)
sportType = json["sport_type"].strava(SportType.self)
profileMedium = URL(optionalString: json["profile_medium"].string)
profile = URL(optionalString: json["profile"].string)
isPrivate = json["private"].bool
memberCount = json["member_count"].int
}
}
| true
|
cb00501b2a8a5bda2a3478f05d04456df7a6ae14
|
Swift
|
fhaoquan/SwiftyParse
|
/Sources/SwiftyParse/StringParser/Extensions.swift
|
UTF-8
| 669
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
//
// Extensions.swift
// SwiftyParse
//
// Created by LZephyr on 2018/6/6.
// Copyright © 2018年 LZephyr. All rights reserved.
//
import Foundation
internal extension Sequence {
/// 判断Sequence是否为空
func isEmpty() -> Bool {
for _ in self {
return false
}
return true
}
}
internal extension Array where Element == Character {
/// 将Array的第一个元素取出来,与剩下的元素组合成一个二元组返回
func decompose() -> (Element?, [Element]) {
if let first = self.first {
return (first, Array(self.dropFirst()))
}
return (nil, self)
}
}
| true
|
6449009a3797a6708ff472e86e0aaee8518b2b22
|
Swift
|
eurofurence/ef-app_ios
|
/Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Objects/Entities/AcceptingEventFeedback.swift
|
UTF-8
| 778
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
class AcceptingEventFeedback: EventFeedback {
private static let defaultStarRating = 3
private let eventBus: EventBus
private let eventIdentifier: EventIdentifier
var feedback: String
var starRating: Int
init(eventBus: EventBus, eventIdentifier: EventIdentifier) {
self.eventBus = eventBus
self.eventIdentifier = eventIdentifier
feedback = ""
starRating = AcceptingEventFeedback.defaultStarRating
}
func submit(_ delegate: EventFeedbackDelegate) {
let submitFeedbackEvent = DomainEvent.EventFeedbackReady(
identifier: eventIdentifier,
feedback: self,
delegate: delegate
)
eventBus.post(submitFeedbackEvent)
}
}
| true
|
8c38e6f96e5603327d677e9e0b1f240818a9c02c
|
Swift
|
mlavergn/swiftlog
|
/Sources/log.swift
|
UTF-8
| 10,112
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
/// App struct with package or bundle related helpers
///
/// -todo:
/// Ideally this would leverage the unified logging system but
/// it appears to be broken in 3.0.2
///
/// if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) {
/// logInstance = OSLog(subsystem:subsystem, category:category)
/// os_log("demo", log:logInstance, type:.error)
/// }
///
/// - author: Marc Lavergne <mlavergn@gmail.com>
/// - copyright: 2017 Marc Lavergne. All rights reserved.
/// - license: MIT
import Foundation
#if os(Linux)
import Glibc
#else
import os.log
import Darwin
#endif
/// Log levels
///
/// - ALL: No filtering of log messages
/// - DEBUG: Debug level or more severe
/// - INFO: Info level or more severe
/// - WARN: Warn level or more severe
/// - ERROR: Error level or more severe
/// - FATAL: Fatal level or more severe
/// - OFF: No log messages
public enum LogLevel: Int {
case ALL = 0
case DEBUG
case INFO
case WARN
case ERROR
case FATAL
case OFF
}
/// Log destination
///
/// - STDOUT: Console output
/// - STDERR: Error log and console
/// - FILE: File output
/// - SYSTEM: System log output
public enum LogDestination: Int {
case STDOUT = 0
case STDERR
case FILE
case SYSTEM
}
public struct Log {
/// Filter level
public static var logLevel: LogLevel = LogLevel.WARN
/// Log destination
public static var logDestination: LogDestination = LogDestination.STDOUT
/// os_log logger
public static var logger: OSLog?
/// Timer singleton for performance measurement
public static var timeMark: DispatchTime?
/// Configure the logger
///
/// - Parameters:
/// - level: Filter level for output
/// - destination: Log destination
public static func configure(level: LogLevel, destination: LogDestination = .STDOUT, _ subssystem: String? = Bundle.main.bundleIdentifier, _ category: String? = nil) {
logLevel = level
logDestination = destination
// experimental support for os_log
if #available(macOS 10.12, *) {
if destination == .SYSTEM {
if subssystem != nil && category != nil {
logger = OSLog(subsystem: subssystem!, category: category!)
}
}
} else {
// send out back to STDOUT
logDestination = .STDOUT
}
}
/// Read logger environment variables and adjust settings
public static func readEnv() {
// (todo) this should be read via a timer
if let value = ProcessInfo.processInfo.environment["LOG_LEVEL"] {
if let valInt = Int(value) {
if let valLogLevel = LogLevel(rawValue: valInt) {
logLevel = valLogLevel
}
}
}
if let value = ProcessInfo.processInfo.environment["LOG_DEST"] {
if let valInt = Int(value) {
if let valLogDestination = LogDestination(rawValue: valInt) {
logDestination = valLogDestination
}
}
}
}
public static var pathURL: URL {
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) {
#if os(iOS) || os(tvOS)
var pathURL = URL(fileURLWithPath: NSHomeDirectory())
#else
var pathURL = FileManager.default.homeDirectoryForCurrentUser
#endif
pathURL = pathURL.appendingPathComponent("log/swift")
do {
try FileManager.default.createDirectory(atPath: pathURL.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
fputs("\(Date.timeIntervalSinceReferenceDate) Log.pathURL failed: \(error)\n", __stderrp)
}
return pathURL
} else {
return URL(fileURLWithPath: "/tmp")
}
}
@inline(__always) public static func logLevelToOSLogType(level: LogLevel) -> OSLogType {
if #available(macOS 10.12, *) {
var oslogType: OSLogType = .debug
switch level {
case .DEBUG:
oslogType = .debug
case .INFO:
oslogType = .info
case .WARN:
oslogType = .default
case .ERROR:
oslogType = .error
case .FATAL:
oslogType = .fault
default:
oslogType = .debug
}
return oslogType
}
return OSLogType(0)
}
/// Outputs a log message to the set destination
///
/// - Parameter message: description as a String
@inline(__always) public static func output(level: LogLevel, file: String, function: String, line: Int, message: String) {
let fileName = (file as NSString).lastPathComponent
switch logDestination {
case .STDOUT:
fputs("\(Date.timeIntervalSinceReferenceDate) [\(fileName).\(function):\(line)] \(message)\n", __stdoutp)
case .STDERR:
fputs("\(Date.timeIntervalSinceReferenceDate) [\(fileName).\(function):\(line)] \(message)\n", __stderrp)
case .SYSTEM:
if #available(macOS 10.12, *) {
let oslogType = logLevelToOSLogType(level: level)
os_log("[%{public}@.%{public}@:%{public}d] %{public}@", log: logger ?? .default, type: oslogType, fileName, function, line, message)
}
case .FILE:
do {
try "\(Date.timeIntervalSinceReferenceDate) [\(fileName).\(function):\(line)] \(message)\n".write(to: pathURL, atomically: false, encoding: String.Encoding.utf8)
} catch let error as NSError {
fputs("\(Date.timeIntervalSinceReferenceDate) file write failed [\(fileName).\(function):\(line)] \(error)\n", __stderrp)
}
}
}
/// Debug level log message
///
/// - Parameter message: description as a String optional
@inline(__always) public static func debug(_ message: String?, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.DEBUG.rawValue {
if let message = message {
output(level: .DEBUG, file: file, function: function, line: line, message: message)
} else {
output(level: .DEBUG, file: file, function: function, line: line, message: "<empty optional>")
}
}
}
/// Debug level log message
///
/// - Parameter object: Any optional to print as a debug string
@inline(__always) public static func debug(_ object: Any?, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.DEBUG.rawValue {
if let object = object as AnyObject? {
output(level: .DEBUG, file: file, function: function, line: line, message: object.debugDescription)
} else {
output(level: .DEBUG, file: file, function: function, line: line, message: "<empty optional>")
}
}
}
/// Information level log message
///
/// - Parameter message: description as a String
@inline(__always) public static func info(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.INFO.rawValue {
output(level: .INFO, file: file, function: function, line: line, message: message)
}
}
/// Warning level log message
///
/// - Parameter message: description as a String
@inline(__always) public static func warn(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.WARN.rawValue {
output(level: .WARN, file: file, function: function, line: line, message: message)
}
}
/// Warning level log message
///
/// - Parameter error: Error object
@inline(__always) public static func warn(_ error: Error, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.WARN.rawValue {
output(level: .WARN, file: file, function: function, line: line, message: String(describing: error))
}
}
/// Error level log message
///
/// - Parameter message: description as a String
static public func error(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.ERROR.rawValue {
output(level: .ERROR, file: file, function: function, line: line, message: message)
}
}
/// Error level log message
///
/// - Parameter error: Error object
static public func error(_ error: Error, file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.ERROR.rawValue {
output(level: .ERROR, file: file, function: function, line: line, message: String(describing: error))
}
}
/// Fatal level log message
///
/// - Parameter message: description as a String
static public func fatal(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
output(level: .FATAL, file: file, function: function, line: line, message: message)
}
/// Outputs the file, function, and line stamp to stdout
///
/// - Parameters:
/// - function: function name as a String (should not be provided)
/// - file: file name as a String (should not be provided)
/// - line: line as an Int (should not be provided)
@inline(__always) public static func stamp(file: String = #file, function: String = #function, line: Int = #line) {
if logLevel.rawValue <= LogLevel.DEBUG.rawValue {
output(level: .DEBUG, file: file, function: function, line: line, message: "<empty optional>")
}
}
/// Saves the content String to file at $HOME/log/swift/<epoch>.log
///
/// - Parameter message: output as a String
public static func dumpFile(output: String) {
if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) {
#if os(iOS) || os(tvOS)
var pathURL = URL(fileURLWithPath: NSHomeDirectory())
#else
var pathURL = FileManager.default.homeDirectoryForCurrentUser
#endif
pathURL = pathURL.appendingPathComponent("log/swift")
do {
try FileManager.default.createDirectory(atPath: pathURL.path, withIntermediateDirectories: true, attributes: nil)
let epoch = NSDate().timeIntervalSince1970
pathURL = pathURL.appendingPathComponent("\(epoch).log")
try output.write(to: pathURL, atomically: false, encoding: String.Encoding.utf8)
} catch let error as NSError {
print(error)
}
}
}
/// Resets the elapsed time marker to being a new measurement
public static var timerMark: Void {
timeMark = DispatchTime.now()
}
/// Measures the elapsed time since the last mark in milliseconds
public static var timerMeasure: Void {
if let timeMark = timeMark {
let timeInterval = Double(DispatchTime.now().uptimeNanoseconds - timeMark.uptimeNanoseconds) / 1_000_000
output(level: .DEBUG, file: "", function: "", line: -1, message: "ELAPSED [\(timeInterval)]ms")
}
}
}
| true
|
873f1c9c572ef1936e3ce8a2236294cecab724f8
|
Swift
|
StydeNet/swift
|
/16 StarWarsApp/StarWarsApp/StarWarsApp/ViewController.swift
|
UTF-8
| 2,701
| 2.9375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// StarWarsApp
//
// Created by Jorge Jimenez on 8/21/16.
// Copyright © 2016 xadrijo. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var hairColorLabel: UILabel!
@IBOutlet weak var eyeColorLabel: UILabel!
@IBOutlet weak var genderLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let swEndpoint = "http://swapi.co/api/people/2/"
guard let url = NSURL(string: swEndpoint) else {
print("No se pudo crear el URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) { (data: NSData?, response:
NSURLResponse?, error: NSError?) in
guard let responseData = data else {
print("Data no recibida")
return
}
do {
guard let people = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String : AnyObject] else {
print("Error tratando de convertir a JSON")
return
}
print(people["name"])
print(people["height"])
print(people["hair_color"])
print(people["eye_color"])
print(people["gender"])
let peopleName = people["name"] as? String
let peopleHeight = people["height"] as? String
let peopleHairColor = people["hair_color"] as? String
let peopleEyeColor = people["eye_color"] as? String
let peopleGender = people["gender"] as? String
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.updateUI(peopleName!, height: peopleHeight!, hairColor: peopleHairColor!, eyeColor: peopleEyeColor!, gender: peopleGender!)
})
} catch {
print("Error tratando de convertir a JSON")
}
}
task.resume()
}
func updateUI(name: String, height: String, hairColor: String, eyeColor: String, gender: String) {
nameLabel.text = name
heightLabel.text = height
hairColorLabel.text = hairColor
eyeColorLabel.text = eyeColor
genderLabel.text = gender
}
}
| true
|
595b69f934c347ac2cb48c5ae17075bfbafc98b7
|
Swift
|
HamstringAssassin/GettingStartedWithSwift
|
/GettingStartedSwift/GettingStartedSwift/SimpleClass.swift
|
UTF-8
| 364
| 2.6875
| 3
|
[] |
no_license
|
//
// SimpleClass.swift
// GettingStartedSwift
//
// Created by O'Connor, Alan on 26/11/2015.
// Copyright © 2015 CodeBiscuits. All rights reserved.
//
import Foundation
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple Class"
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted"
}
}
| true
|
1d44b2ae4527ad872e2fde97ae0d2fdf1ed2cc08
|
Swift
|
rtitco/comp3097-group-project
|
/final-submission/foodbowl-ios/foodbowl-ios/AddViewController.swift
|
UTF-8
| 6,632
| 2.546875
| 3
|
[] |
no_license
|
import Foundation
import UIKit
import CoreData
class AddViewController: UIViewController {
//let validityType: String.ValidityType = .phone
@IBOutlet weak var lbl_AddTitle: UILabel!
@IBOutlet weak var lbl_Name: UILabel!
@IBOutlet weak var txt_Name: UITextField!
@IBOutlet weak var txt_Address: UITextField!
@IBOutlet weak var txt_City: UITextField!
@IBOutlet weak var txt_Province: UITextField!
@IBOutlet weak var txt_Country: UITextField!
@IBOutlet weak var txt_Phone: UITextField!
@IBOutlet weak var txt_Desc: UITextView!
@IBOutlet weak var txt_Tags: UITextField!
@IBOutlet weak var txt_Rating: UITextField!
@IBOutlet weak var lbl_Message: UILabel!
@IBOutlet weak var err_name: UILabel!
@IBOutlet weak var err_address: UILabel!
@IBOutlet weak var err_city: UILabel!
@IBOutlet weak var err_province: UILabel!
@IBOutlet weak var err_country: UILabel!
@IBOutlet weak var err_phone: UILabel!
@IBOutlet weak var err_description: UILabel!
@IBOutlet weak var err_tags: UILabel!
@IBOutlet weak var err_rating: UILabel!
@IBAction func saveRestaurant(_ sender: UIButton) {
let name: String! = txt_Name.text
let address: String! = txt_Address.text
let city: String! = txt_City.text
let province: String! = txt_Province.text
let country: String! = txt_Country.text
let phone: String! = txt_Phone.text
let desc: String! = txt_Desc.text
let tags: String! = txt_Tags.text
let rating: String! = txt_Rating.text
var isFormValid = true
errFieldReset()
//if set to false do dont submit
if !name.isValid(.name){
isFormValid = false
err_name.text = "Invalid Name."
}
if !address.isValid(.address){
isFormValid = false
err_address.text = "Invalid Address"
}
if !city.isValid(.city){
isFormValid = false
err_city.text = "Invalid City"
}
if !province.isValid(.province){
isFormValid = false
err_province.text = "Invalid Province"
}
if !country.isValid(.country){
isFormValid = false
err_country.text = "Invalid Country"
}
if !phone.isValid(.phone){
isFormValid = false
err_phone.text = "Invalid Phone Number"
}
if !desc.isValid(.desc){
isFormValid = false
err_description.text = "Invalid Description"
}
if !tags.isValid(.tags){
isFormValid = false
err_tags.text = "Invalid Tags"
}
if !rating.isValid(.rating){
isFormValid = false
err_rating.text = "Invalid Rating"
}
//if passed all field checks send away!
if(isFormValid){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
if let entity = NSEntityDescription.entity(forEntityName: "Restaurant", in: context){
let restaurant = NSManagedObject(entity:entity, insertInto: context)
restaurant.setValue(name, forKeyPath: "name")
restaurant.setValue(address, forKeyPath: "address")
restaurant.setValue(city, forKeyPath: "city")
restaurant.setValue(province, forKeyPath: "province")
restaurant.setValue(country, forKeyPath: "country")
restaurant.setValue(phone, forKeyPath: "phone")
restaurant.setValue(desc, forKeyPath: "desc")
restaurant.setValue(tags, forKeyPath: "tags")
restaurant.setValue(rating, forKeyPath: "rating")
do {
try context.save()
lbl_Message.text = "Save Successful.";
//restaurantList.append(restaurant)
} catch let error as NSError {
lbl_Message.text = "Save Failed.";
print("Could not save. \(error), \(error.userInfo)")
}
}
}
else{
lbl_Message.text = "Invalid Fields."
}
}
func errFieldReset(){
err_name.text = "";
err_address.text = "";
err_city.text = "";
err_province.text = "";
err_country.text = "";
err_phone.text = "";
err_description.text = "";
err_tags.text = "";
err_rating.text = "";
}
override func viewDidLoad() {
super.viewDidLoad()
lbl_Message.text = "";
errFieldReset()
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
}
}
extension String {
enum ValidityType {
case name
case address
case city
case province
case country
case phone
case desc
case tags
case rating
}
enum Regex: String {
case str = "^[A-Za-z]{1,}([- ]*[A-Za-z]{1,}){0,}$";
case phone = "^[0-9]{10}$";
case address = "^[0-9]{1,5}[ ]{1}[A-Za-z]{1,}([ ]{1}[A-Za-z]{2,}){1,}([ ]{1}[A-Za-z]{0,1}){0,1}([,]{0,1}[ ]{1}[A-Za-z]{4,} [ ]{1} [0-9]{1,}){0,1}$";
case tags = "^[A-Za-z]{1,}([- ]*[A-Za-z]{1,}){0,}([,]{1}[ ]{0,1}[A-Za-z]{1,}([- ]*[A-Za-z]{1,}){0,})*$";
case rating = "^[0-5]{1}$";
}
func isValid(_ validityType: ValidityType)->Bool{
let format = "SELF MATCHES %@"
var regex = ""
switch validityType {
case .name:
regex = Regex.str.rawValue
case .address:
regex = Regex.address.rawValue
case .city:
regex = Regex.str.rawValue
case .province:
regex = Regex.str.rawValue
case .country:
regex = Regex.str.rawValue
case .phone:
regex = Regex.phone.rawValue
case .desc:
regex = Regex.str.rawValue
case .tags:
regex = Regex.tags.rawValue
case .rating:
regex = Regex.rating.rawValue
}
return NSPredicate(format: format, regex).evaluate(with: self)
}
}
| true
|
143ec06cb0bdb059f4e7c76312ff73eb5aee91ad
|
Swift
|
agg23/SwiftNES
|
/SwiftNES/Implementation/Utility.swift
|
UTF-8
| 319
| 2.796875
| 3
|
[] |
no_license
|
//
// Utility.swift
// SwiftNES
//
// Created by Adam Gastineau on 9/30/17.
// Copyright © 2017 Adam Gastineau. All rights reserved.
//
import Foundation
extension Array {
subscript(i: UInt16) -> Element {
get {
return self[Int(i)]
} set(from) {
self[Int(i)] = from
}
}
}
| true
|
c11997c003fb36b9f9762f11daa64f5c03113c68
|
Swift
|
alperenarc/final-project-alperenarc
|
/GameApp/GameApp/Screen/WishList/WishListViewModel.swift
|
UTF-8
| 5,864
| 2.53125
| 3
|
[] |
no_license
|
//
// WishListViewModel.swift
// GameApp
//
// Created by Alperen Arıcı on 28.05.2021.
//
import Foundation
import CoreData
import CoreNetwork
extension WishListViewModel {
enum Constants {
static let wishListEntityName = "WishList"
static let clickedGameEntityName = "ClickedGame"
}
}
protocol WishListViewModelProtocol {
var delegate: WishListViewModelDelegate? { get set }
var wishList: [GameResult] { get }
func currentGame(at index: Int) -> GameResult
func load()
func wishListContains(id: Int?) -> Bool
func removeWishList(id: Int)
func fetchClickedGames()
func clickedGameListContains(id: Int?) -> Bool
}
protocol WishListViewModelDelegate: AnyObject {
func getAppDelegate() -> AppDelegate
func alertShow(title: String, action: String, message: String)
func showLoadingView()
func hideLoadingView()
func reloadData()
func showEmptyCollectionView()
func restoreCollectionView()
}
final class WishListViewModel {
let networkManager: NetworkManager<EndpointItem>
weak var delegate: WishListViewModelDelegate?
lazy var appDelegate = delegate?.getAppDelegate()
lazy var context: NSManagedObjectContext = appDelegate!.persistentContainer.viewContext
private var wishListCoreData: [WishListItem] = []
private var wishGames: [GameResult] = []
private var clickedGameList: [ClickedGameItem] = []
init(networkManager: NetworkManager<EndpointItem>) {
self.networkManager = networkManager
}
private func fetchGame(id: NSNumber, completion: @escaping () -> ()) {
networkManager.request(endpoint: .game(id: id as! Int), type: Game.self) { [weak self] result in
switch result {
case .success(let response):
let gameResult = GameResult(id: response.id ?? 0,
name: response.name ?? "",
image: response.backgroundImage ?? "")
if self?.wishGames.count == 0 {
self?.wishGames = [gameResult]
} else {
self?.wishGames.append(gameResult)
}
completion()
break
case .failure(let error):
print(error)
break
}
}
}
private func fetchWishList(completion: @escaping () -> ()) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.wishListEntityName)
do {
let results: NSArray = try context.fetch(request) as NSArray
for result in results {
let wishListItem = result as! WishListItem
wishListCoreData.append(wishListItem)
}
completion()
} catch {
delegate?.alertShow(title: "Warning", action: "Ok", message: "Fetch Failed !")
}
}
private func deleteWishListFromDB(id: Int) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.wishListEntityName)
request.predicate = NSPredicate.init(format: "id==\(id)")
do {
let results: NSArray = try context.fetch(request) as NSArray
for object in results {
context.delete(object as! NSManagedObject)
}
try context.save()
} catch _ {
delegate?.alertShow(title: "Warning", action: "Ok", message: "An error was occured while deleting !")
}
}
private func prepareWisList(completion: @escaping () -> ()) {
let wishSet = Set(wishListCoreData.map { $0.id })
if wishSet.isEmpty {
delegate?.showEmptyCollectionView()
delegate?.reloadData()
return
} else {
delegate?.restoreCollectionView()
delegate?.reloadData()
}
let wishGameAsyncGroup: DispatchGroup = DispatchGroup()
for wishGame in wishSet {
wishGameAsyncGroup.enter()
guard let game = wishGame else { return }
fetchGame(id: game as NSNumber) {
wishGameAsyncGroup.leave()
}
}
wishGameAsyncGroup.notify(queue: DispatchQueue.main) {
completion()
}
}
}
extension WishListViewModel: WishListViewModelProtocol {
func load() {
wishListCoreData = []
wishGames = []
fetchClickedGames()
delegate?.showLoadingView()
fetchWishList { [weak self] in
self?.prepareWisList {
self?.delegate?.hideLoadingView()
self?.delegate?.reloadData()
}
}
}
func fetchClickedGames() {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constants.clickedGameEntityName)
do {
let results: NSArray = try context.fetch(request) as NSArray
for result in results {
let clickedGame = result as! ClickedGameItem
clickedGameList.append(clickedGame)
}
} catch {
print("Fetch failed !")
}
}
func clickedGameListContains(id: Int?) -> Bool {
guard let id = id else { return false }
return clickedGameList.contains { $0.id == id as NSNumber }
}
var wishList: [GameResult] { wishGames }
func currentGame(at index: Int) -> GameResult { wishGames[index] }
func wishListContains(id: Int?) -> Bool {
guard let id = id else { return false }
return wishListCoreData.contains { $0.id == id as NSNumber }
}
func removeWishList(id: Int) {
deleteWishListFromDB(id: id)
wishGames = wishGames.filter { $0.id != id }
if wishGames.isEmpty {
delegate?.showEmptyCollectionView()
} else {
delegate?.restoreCollectionView()
}
delegate?.reloadData()
}
}
| true
|
ed868a42b452a52576fdf5dc59f922c21709359f
|
Swift
|
djud17/bsWear-shop
|
/bsWear-shop/Servises/ApiClientImpl.swift
|
UTF-8
| 1,747
| 2.984375
| 3
|
[] |
no_license
|
//
// ApiClientImpl.swift
// bsWear-shop
//
// Created by Давид Тоноян on 01.07.2021.
//
import Foundation
import Alamofire
protocol ApiClient {
func getCategories(completion: @escaping ([ProductCategory]) -> Void)
func getProducts(_ id: String, completion: @escaping ([Product]) -> Void)
}
class ApiClientImpl: ApiClient {
func getCategories(completion: @escaping ([ProductCategory]) -> Void) {
var categories: [ProductCategory] = []
let url = URL(string: "https://blackstarshop.ru/index.php?route=api/v1/categories")!
AF.request(url).responseJSON { response in
if let objects = response.value ,
let jsonDict = objects as? NSDictionary {
for (_, data) in jsonDict where data is NSDictionary{
if let category = ProductCategory(data: data as! NSDictionary) {
categories.append(category)
}
}
completion(categories)
}
}
}
func getProducts(_ categoryId: String, completion: @escaping ([Product]) -> Void) {
let url = URL(string: "https://blackstarshop.ru/index.php?route=api/v1/products&cat_id=\(categoryId)")!
var products: [Product] = []
AF.request(url).responseJSON { response in
if let objects = response.value ,
let jsonDict = objects as? NSDictionary {
for (_, data) in jsonDict where data is NSDictionary{
if let product = Product(data: data as! NSDictionary) {
products.append(product)
}
}
completion(products)
}
}
}
}
| true
|
6acf82bf85aec77145c3ea45e08be79399d330c3
|
Swift
|
stephredrx/Gary-Portal-iOS
|
/GaryPortal/Assets/Views/Camera/GPCamera.swift
|
UTF-8
| 24,123
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// GPCamera.swift
// GaryPortal
//
// Created by Tom Knighton on 11/02/2021.
//
import SwiftUI
import AVFoundation
import Photos
struct CameraView: View {
@StateObject var camera = CameraModel()
@GestureState private var isPressingDown: Bool = false
@State var isShowingEditor = false
@State var timeLimit = 30
@State var allowsGallery = true
@State var allowsVideo = true
enum ActiveSheet: Identifiable {
case none, picker, stickers
var id: ActiveSheet { self }
}
@State var activeSheet: ActiveSheet?
var onFinalAction: (_ success: Bool, _ isVideo: Bool, _ urlToMedia: URL?) -> ()
init(timeLimit: Int = 30, allowsGallery: Bool = true, allowsVideo: Bool = true, _ finishedEditing: @escaping(_ success: Bool, _ isVideo: Bool, _ urlToMedia: URL?) -> ()) {
self.onFinalAction = finishedEditing
self.timeLimit = timeLimit
self.allowsGallery = allowsGallery
self.allowsVideo = allowsVideo
}
var body: some View {
ZStack {
CameraPreview(camera: camera)
.ignoresSafeArea(.all, edges: .all)
.onTapGesture(count: 2) {
if !self.camera.isRecording && !self.camera.isTaken {
self.camera.toggleCamera()
}
}
VStack {
HStack {
Spacer().frame(width: 8)
Button(action: { self.onFinalAction(false, false, nil) }, label: {
Image(systemName: "xmark.circle")
.foregroundColor(.primary)
.padding()
.background(Color("Section").opacity(0.6))
.clipShape(Circle())
})
.if(self.camera.isRecording) { $0.hidden() }
.padding(10)
Spacer()
if !camera.isTaken && !camera.isRecording {
Button(action: { self.camera.toggleFlash() }, label: {
Image(systemName: self.camera.flashModeImageName)
.foregroundColor(.primary)
.padding()
.background(Color("Section").opacity(0.6))
.clipShape(Circle())
})
.padding(10)
Spacer().frame(width: 16)
Button(action: { self.camera.toggleCamera() }, label: {
Image(systemName: "arrow.triangle.2.circlepath.camera")
.foregroundColor(.primary)
.padding()
.background(Color("Section").opacity(0.6))
.clipShape(Circle())
})
.padding(10)
}
}
HStack {
if !camera.isTaken && !camera.isRecording && self.allowsGallery {
Spacer()
Button(action: { self.activeSheet = .picker }, label: {
Image(systemName: "photo.on.rectangle.angled")
.foregroundColor(.primary)
.padding()
.background(Color("Section").opacity(0.6))
.clipShape(Circle())
})
.padding(10)
}
}
Spacer()
HStack {
if !camera.isTaken {
Button(action: { }, label: {
ZStack {
Circle()
.fill(self.camera.isRecording ? Color.red : Color.white)
.frame(width: self.camera.isRecording ? 85 : 65, height: self.camera.isRecording ? 85 : 65)
.animation(.easeInOut)
Circle()
.stroke(self.camera.isRecording ? Color.red :Color.white, lineWidth: 2)
.frame(width: self.camera.isRecording ? 95 : 75, height: self.camera.isRecording ? 95 : 85)
.animation(.easeInOut)
}
.onTapGesture(perform: {
self.camera.takePic()
})
})
.if(allowsVideo) {
$0.simultaneousGesture(
LongPressGesture(minimumDuration: 1.0)
.sequenced(before: LongPressGesture(minimumDuration: .infinity))
.updating($isPressingDown, body: { (value, state, transaction) in
switch value {
case .second(true, nil):
state = true
default: break
}
})
)
}
}
}
.frame(height: 75)
.onChange(of: self.isPressingDown, perform: { value in
if value { self.camera.startRecording() }
else { self.camera.stopRecording() }
})
}
if self.camera.shouldShowEditor {
MediaEditor(isShowing: Binding(get: { camera.shouldShowEditor } , set: { camera.shouldShowEditor = $0 }), activeSheet: self.$activeSheet, isVideo: self.camera.outputURL != nil, photoData: self.camera.picData, videoURL: self.camera.outputURL, wasFromLibrary: self.camera.wasFromLibrary, cameraUsed: self.camera.currentCamera, action: self.onFinalAction)
.onDisappear {
self.camera.reTake()
}
}
}
.onAppear {
camera.checkAccess(self.timeLimit)
}
.sheet(item: $activeSheet) { item in
if item == .picker {
MediaPicker(limit: 1, filter: allowsVideo ? .imagesAndVideos : .images) { (didPick, items) in
self.activeSheet = nil
if didPick {
if let items = items, let item = items.items.first {
if item.mediaType == .photo {
guard let imageData = item.photo?.jpegData(compressionQuality: 0.7) else { return }
DispatchQueue.global(qos: .background).async {
self.camera.session.stopRunning()
}
self.camera.picData = imageData
self.camera.isTaken = true
self.camera.wasFromLibrary = true
self.camera.shouldShowEditor = true
} else if item.mediaType == .video {
DispatchQueue.main.async {
self.camera.session.stopRunning()
self.camera.outputURL = item.url
self.camera.isRecording = false
self.camera.picData = Data(count: 0)
self.camera.isTaken = true
self.camera.wasFromLibrary = true
self.camera.shouldShowEditor = true
}
}
}
}
}
} else if item == .stickers {
StickerPickerView() { url in
self.activeSheet = nil
self.notifyAddSticker(url)
}
}
}
.alert(isPresented: $camera.alert, content: {
Alert(title: Text("Please enable camera"))
})
}
func notifyAddSticker(_ url: String) {
NotificationCenter.default.post(name: .addStickerLabelPressed, object: url)
}
}
struct MediaEditor: View {
@Environment(\.presentationMode) var presentationMode
var isVideo = false
var photoData: Data?
var videoURL: URL?
var cameraUsed: CameraPosition
var wasFromLibrary: Bool
@Binding var isShowing: Bool
@Binding var activeSheet: CameraView.ActiveSheet?
@State private var play = true
@State private var chosenColour: Color = .clear
@State private var drawingImage = UIImage()
@State private var isInDrawingMode = false
@State private var didDraw = false
@State private var subviewCount = 0
@State private var overlayView = UIImage()
@State private var showStickerView = false
var onFinishedEditing: (_ success: Bool, _ isVideo: Bool, _ urlToMedia: URL?) -> ()
init(isShowing: Binding<Bool>, activeSheet: Binding<CameraView.ActiveSheet?>, isVideo: Bool = false, photoData: Data? = nil, videoURL: URL? = nil, wasFromLibrary: Bool, cameraUsed: CameraPosition, action: @escaping (_ success: Bool, _ isVideo: Bool, _ urlToMedia: URL?) -> ()) {
self.isVideo = isVideo
self.photoData = photoData
self.videoURL = videoURL
self.cameraUsed = cameraUsed
self.onFinishedEditing = action
self.wasFromLibrary = wasFromLibrary
self._isShowing = isShowing
self._activeSheet = activeSheet
}
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .top) {
Color.black.edgesIgnoringSafeArea(.all)
if isVideo {
PlayerView(url: videoURL?.absoluteString ?? "", play: $play, gravity: self.wasFromLibrary ? .fit : .fill)
.if(self.cameraUsed == .front) { $0.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0)) }
.frame(width: geometry.size.width, height: geometry.size.height)
} else {
if let photoData = self.photoData {
Image(uiImage: UIImage(data: photoData) ?? UIImage())
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width, height: geometry.size.height)
.if(self.cameraUsed == .front) { $0.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0)) }
}
}
if !self.isVideo || (self.isVideo && !self.wasFromLibrary) {
DrawingViewRepresentable(isDrawing: $isInDrawingMode, finalImage: $drawingImage, didDraw: $didDraw)
.frame(width: geometry.size.width, height: geometry.size.height)
.edgesIgnoringSafeArea(.all)
}
CamTextViewRepresentable(subviewCount: $subviewCount, overlayViewImage: $overlayView)
.frame(width: geometry.size.width, height: geometry.size.height)
.edgesIgnoringSafeArea(.all)
.disabled(isInDrawingMode)
.allowsHitTesting(!isInDrawingMode)
VStack {
if !isInDrawingMode {
HStack(alignment: .top) {
Spacer().frame(width: 8)
Button(action: { self.isShowing = false }, label: {
Image(systemName: "xmark.circle")
.foregroundColor(.primary)
.padding()
.background(Color("Section"))
.clipShape(Circle())
.padding(.top, 24)
})
Spacer()
VStack {
Button(action: { self.isInDrawingMode = true }, label: {
Image(systemName: "pencil.and.outline")
.foregroundColor(.primary)
.padding()
.background(Color("Section"))
.clipShape(Circle())
.padding(.top, 24)
})
.if(self.isVideo && self.wasFromLibrary) { $0.hidden() }
Spacer().frame(height: 16)
Button(action: { self.notifyAddText() }, label: {
Image(systemName: "text.cursor")
.foregroundColor(.primary)
.padding()
.background(Color("Section"))
.clipShape(Circle())
.padding(.top, 24)
})
Spacer().frame(height: 16)
Button(action: { self.activeSheet = .stickers }, label: {
Image(systemName: "mustache")
.foregroundColor(.primary)
.padding(20)
.background(Color("Section"))
.clipShape(Circle())
})
}
Spacer().frame(width: 16)
}
.animation(.easeInOut)
.padding(.top, 32)
} else {
HStack(alignment: .top) {
Spacer()
Button(action: { self.isInDrawingMode = false }, label: {
Image(systemName: "xmark.circle")
.foregroundColor(.primary)
.padding()
.background(Color("Section"))
.clipShape(Circle())
.padding(.top, 24)
})
Spacer().frame(width: 16)
}
.animation(.easeInOut)
.padding(.top, 32)
}
Spacer()
if !isInDrawingMode {
HStack {
Spacer()
Button(action: { finishEditing() }, label: {
HStack {
Text("Next")
.fontWeight(.semibold)
Image(systemName: "arrow.right")
}
.foregroundColor(.black)
.padding(.vertical, 10)
.padding(.horizontal, 20)
.background(Color.white)
.clipShape(Capsule())
})
.padding(.leading)
Spacer().frame(width: 8)
}
}
Spacer().frame(height: 32)
}
}
}
.edgesIgnoringSafeArea(.all)
}
func finishEditing() {
if isVideo {
guard let videoURL = self.videoURL else { self.onFinishedEditing(false, true, nil); return }
let asset = AVURLAsset(url: videoURL)
let merge = Merge(config: MergeConfiguration(frameRate: 30, directory: NSTemporaryDirectory(), quality: .high, placement: .stretchFit))
merge.overlayVideo(video: asset, overlayImages: [self.drawingImage, self.overlayView]) { (url) in
self.onFinishedEditing(true, true, url)
} progressHandler: { (_) in }
} else {
if let photoData = self.photoData {
let oldImage = UIImage(data: photoData)
let newImage = oldImage?.imageByCombiningImage(withImage: self.drawingImage)
let imageWithTexts = newImage?.imageByCombiningImage(withImage: self.overlayView)
let fileUrl = imageWithTexts?.saveImageToDocumentsDirectory(withName: UUID().uuidString)
if let url = URL(string: fileUrl ?? "") {
self.onFinishedEditing(true, false, url)
} else {
self.onFinishedEditing(false, false, nil)
}
}
}
}
func notifyAddText() {
NotificationCenter.default.post(name: .addTextLabelPressed, object: nil)
}
}
class DrawingView: UIView, GPColourPickerDelegate {
func changedColour(to colour: UIColor) {
self.colour = Color(colour.cgColor)
}
var lastPoint: CGPoint = .zero
var colour: Color = .black
var brushWidth: CGFloat = 10
var opacity: CGFloat = 1
var swiped = false
var isDrawing = false
var mainImageView = UIImageView()
var tempImageView = UIImageView()
var imageSteps = [UIImage]()
var colourPickerView: UIView?
var backButton: UIButton?
var delegate: DrawingViewProtocol?
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(mainImageView)
self.addSubview(tempImageView)
self.mainImageView.bindFrameToSuperviewBounds()
self.tempImageView.bindFrameToSuperviewBounds()
let hostVC = GPColourPicker(frame: CGRect(x: 0, y: 0, width: 0, height: 0), delegate: self)
self.colourPickerView = hostVC
if let colourview = self.colourPickerView {
self.addSubview(colourview)
self.bringSubviewToFront(colourview)
colourview.backgroundColor = .clear
colourview.translatesAutoresizingMaskIntoConstraints = false
colourview.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 16).isActive = true
colourview.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
colourview.heightAnchor.constraint(equalToConstant: 100).isActive = true
}
self.backButton = UIButton()
backButton?.translatesAutoresizingMaskIntoConstraints = false
let largeConfig = UIImage.SymbolConfiguration(pointSize: 22, weight: .bold, scale: .large)
let backImage = UIImage(systemName: "arrow.uturn.backward", withConfiguration: largeConfig)
backButton?.setImage(backImage?.withRenderingMode(.alwaysTemplate), for: .normal)
backButton?.tintColor = .white
self.addSubview(backButton ?? UIButton())
self.bringSubviewToFront(backButton ?? UIButton())
backButton?.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16).isActive = true
backButton?.topAnchor.constraint(equalTo: self.topAnchor, constant: 72).isActive = true
backButton?.heightAnchor.constraint(equalToConstant: 45).isActive = true
backButton?.widthAnchor.constraint(equalToConstant: 45).isActive = true
backButton?.backgroundColor = .clear
backButton?.addTarget(self, action: #selector(self.backButtonPressed(_:)), for: .touchUpInside)
}
public func toggleDrawing(mode: Bool) {
self.isDrawing = mode
self.colourPickerView?.isHidden = !mode
self.backButton?.isHidden = !mode
}
@objc
func backButtonPressed(_ sender: UIButton) {
self.mainImageView.image = self.imageSteps.popLast()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, self.isDrawing == true else { return }
swiped = false
lastPoint = touch.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, self.isDrawing == true else { return }
swiped = true
let currentPoint = touch.location(in: self)
self.drawLine(from: self.lastPoint, to: currentPoint)
lastPoint = currentPoint
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard self.isDrawing == true else { return }
if !swiped {
self.drawLine(from: self.lastPoint, to: self.lastPoint)
}
UIGraphicsBeginImageContext(self.mainImageView.frame.size)
self.mainImageView.image?.draw(in: self.bounds, blendMode: .normal, alpha: 1.0)
self.tempImageView.image?.draw(in: self.bounds, blendMode: .normal, alpha: self.opacity)
self.mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.tempImageView.image = nil
self.imageSteps.append(self.mainImageView.image ?? UIImage())
self.delegate?.didUpdateImage(self.mainImageView.image ?? UIImage())
}
func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
guard self.isDrawing == true else { return }
UIGraphicsBeginImageContext(self.frame.size)
guard let context = UIGraphicsGetCurrentContext() else { return }
self.tempImageView.image?.draw(in: self.bounds)
context.move(to: fromPoint)
context.addLine(to: toPoint)
context.setLineCap(.round)
context.setBlendMode(.normal)
context.setLineWidth(self.brushWidth)
context.setStrokeColor(UIColor(self.colour).cgColor)
context.strokePath()
self.tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
self.tempImageView.alpha = self.opacity
UIGraphicsEndImageContext()
}
func didChangeColour(to colour: Color) {
self.colour = colour
}
}
protocol DrawingViewProtocol {
func didUpdateImage(_ image: UIImage)
}
struct DrawingViewRepresentable: UIViewRepresentable {
@Binding var isDrawing: Bool
@Binding var finalImage: UIImage
@Binding var didDraw: Bool
func makeUIView(context: Context) -> DrawingView {
let view = DrawingView()
view.isDrawing = isDrawing
view.delegate = context.coordinator
return view
}
func updateUIView(_ uiView: DrawingView, context: Context) {
uiView.toggleDrawing(mode: self.isDrawing)
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator: NSObject, DrawingViewProtocol {
var parent: DrawingViewRepresentable
init(_ parent: DrawingViewRepresentable) {
self.parent = parent
}
func didUpdateImage(_ image: UIImage) {
parent.finalImage = image
self.parent.didDraw = true
}
}
}
| true
|
8d55fdc89643b9dce7758089baa415d78fd4d369
|
Swift
|
YoutacRSBae1-VA/DNS-Configurator
|
/DNS Configurator/View/DoHConfigView.swift
|
UTF-8
| 917
| 2.796875
| 3
|
[] |
no_license
|
//
// DoHConfigView.swift
// DNS Configurator
//
// Created by Takahiko Inayama on 2020/09/21.
//
import SwiftUI
struct DoHConfigView: View {
let config: DoHConfig
var body: some View {
List {
Section(header: Text("Servers")) {
ForEach(config.servers, id: \.hashValue) { server in
Text(server)
}
}
Section(header: Text("Query URL")) {
Text(config.serverURL)
}
}
}
}
struct DoHConfiglView_Previews: PreviewProvider {
@State static var selectedConfig: DoHConfig?
static var previews: some View {
DoHConfigView(config: DoHConfig(servers: [ "8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844" ], serverURL: "https://cloudflare-dns.com/dns-query", displayText: "Google Public DNS"))
}
}
| true
|
1ffda0691860f6c25e24ae373969d0ae36f69528
|
Swift
|
lishengbing/XJExtension
|
/XJExtension/Classes/String_Extension.swift
|
UTF-8
| 591
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// String_Extension.swift
// 新增客户页
//
// Created by lishengbing on 2017/5/23.
// Copyright © 2017年 lishengbing. All rights reserved.
//
import UIKit
public extension String{
func transformToPinYin()->String{
let mutableString = NSMutableString(string: self)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
let string = String(mutableString)
return string.replacingOccurrences(of: " ", with: "").capitalized
}
}
| true
|
4c3164a624094d382a26ea908adf0f3d7ab70058
|
Swift
|
lmsampson/Message-Board-App
|
/Message Board/Message Board/View Controllers/MessageDetailViewController.swift
|
UTF-8
| 1,001
| 2.59375
| 3
|
[] |
no_license
|
//
// MessageDetailViewController.swift
// Message Board
//
// Created by Lisa Sampson on 8/15/18.
// Copyright © 2018 Lisa Sampson. All rights reserved.
//
import UIKit
class MessageDetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func sendButtonWasTapped(_ sender: UIBarButtonItem) {
guard let name = nameTextField.text,
let message = messageTextView.text,
let thread = messageThread else { return }
messageThreadController?.createMessage(thread: thread, text: message, sender: name, completion: { (success) in
DispatchQueue.main.async {
self.navigationController?.popViewController(animated: true)
}
})
}
var messageThread: MessageThread?
var messageThreadController: MessageThreadController?
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var messageTextView: UITextView!
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.