SWIFT - 18. Наследование

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

спасибо большое вам!!!! вы - наш путь в профессию )) с богом, как говорится ))

Dontgoagainstthedream
Автор

Быстро, внятно, без соплей. Отличный урок. Спасибо Алекс Скутаренко)))

nusanrmm
Автор

1. Создайте базовый класс артист с "именем", "фамилией" и методом "выступление". У каждого дочернего класса свой метод "выступление" (актер - играет, клоун - развлекает, танцор - танцует), включающее в себя представление участника, в каком жанре выступление и действие (можно просто вывод строки). Создайте дочерний класс "художник", который не хочет, чтобы его называли вы и всегда ставит другое имя, когда вы пытаетесь его назвать. Положить все экземпляры в один массив и пройдясь по нему вызвать у всех выступление.

2. Базовый класс - "транспортное средство"; свойства - скорость, вместимость, стоимость одной перевозки (все computed properties). Несколько дочерних классов (самолет, корабль, вертолет, машина, поезд) с переопределенными свойствами (для каждого своя скорость вместимость и стоимость). Создать по одному объекту каждому дочернему классу. У всех есть метод, который что-то расчитывает (скорость, расстояние, количество пассажиров), конкретно сколько уйдет денег и времени, чтобы перевести определенное количество человек из пункта А в пункт В. При перевозке 100 и 1000 человек ответить на следующие вопросы:
-Как быстро мы сможем это сделать и каким транспортом?
-Стоимость всех перевозок и количество?
-Какой транспорт быстрее справится и какой более выгодный?

ИванМилосердов-ьй
Автор

Спасибо за крутой плейлист) Swift марафон отличный)

someone_possible
Автор

"У любого хьюмана есть есть 2 руки, 2 ноги.... Нууу, не у любого... У большинства"

shaamee
Автор

//Lesson 18 Inheritance

//Task - 2
// - Create a parent class "Transport" with 3 computed proprietes (speed, seats, one transfer price).
// - Create some subclasses with overriden proprietes (airplane, ship, helicopter, car, train).
// - Create one instance for each Transport Subclass.
// - Each subclass has own method that calculate (speed, distance, number of people).
// - Calculate how much money and time need for transfering a certain number of people from point A to point B (for 100 and 10.000 people).

// Answer:
// 1. How quickly can we do this and by what transport?
// 2. Price and Number of all transfers for each subclass?
// 3. Which transport will do it faster and which is more profitable?

import Foundation

class Transport {

var speed: Int { return 0 }
var seats: Int { return 0 }
var transferPrice: Float { return 0 }

//method to calculate transfer time
func timeForTransfer(distance: Int) -> Float {
return Float(Float(distance) / Float(speed))
}

//method for calculating number of transfers
func numberOfTransfers(for people: Int) -> Float {
return ceil(Float(Float(people) / Float(seats)))
}

//method that calculate total cost for transfering people
func totalCost(for people: Int) -> Float {
return Float(Float(people) * Float(transferPrice))
}
}

class Airplane: Transport {
override var speed: Int { return 903 }
override var seats: Int { return 262 }
override var transferPrice: Float { return 75.5 }
}

class Ship: Transport {
override var speed: Int { return 42 }
override var seats: Int { return 3000 }
override var transferPrice: Float { return 1000.0 }
}

class Helicopter: Transport {
override var speed: Int { return 260 }
override var seats: Int { return 5 }
override var transferPrice: Float { return 112.2 }
}

class Car: Transport {
override var speed: Int { return 140 }
override var seats: Int { return 5 }
override var transferPrice: Float { return 200 }
}

class Train: Transport {
override var speed: Int { return 120 }
override var seats: Int { return 142 }
override var transferPrice: Float { return 100 }
}

var airplane = Airplane()
var ship = Ship()
var helicopter = Helicopter()
var car = Car()
var train = Train()

func compareTransport(dinstance: Int, people: Int) {
let transport: [Transport] = [airplane, ship, helicopter, car, train]

var bestTimeTransport: Transport?
var bestCostTransport: Transport?
var minTime: Float = .greatestFiniteMagnitude
var minCost: Float = .greatestFiniteMagnitude

for transport in transport {
let time = dinstance)
let cost = transport.totalCost(for: people)
let transfers = people)

print("\(type(of: transport)) - Time: \(time) hours, Cost \(cost) USD, Transfers \(transfers)")

if time < minTime {
minTime = time
bestTimeTransport = transport
}

if cost < minCost {
minCost = cost
bestCostTransport = transport
}
}

if let bestCostTransport = bestCostTransport {
print("\nFastest Transport: \(type(of: bestTimeTransport!)) - Time: \(minTime) hours.")
}

if let bestCostTransport = bestCostTransport {
print("Most cost-effective transport: \(type(of: bestCostTransport)) - Cost: \(minCost) USD")
}
}

print("Transfer of 100 people:")
compareTransport(dinstance: 1000, people: 100)

print("\nTransfer of 10 000 people:")
compareTransport(dinstance: 1000, people: 10000)

iacobzanoci
Автор

//Lesson 18 Inheritance
//Task - 3
// - Create 5 different parent classes (human, dog, monkey, giraffe, crocodile).
// 1. Make some instances of each parent class.
// 2. Calculate the number of reptiles, quadrupeds, animals, living beings (E.g. make an array with all reptiles and display how many objects are).
// Important! - The union must be by parent class, not by any object.

class Human {
var race: String

init(race: String) {
self.race = race
}
}

class Dog {
var breed: String

init(breed: String) {
self.breed = breed
}
}

class Monkey {
var specie: String

init(specie: String) {
self.specie = specie
}
}

class Giraffe {
var classification: String

init(classification: String) {
self.classification = classification
}
}

class Crocodile {
var classifications: String

init(classifications: String) {
self.classifications = classifications
}
}

//array of livingBeings
let array: [Any] = [
Human(race: "American Human"),
Human(race: "Ethiopean Human"),
Human(race: "Malay Human"),
Dog(breed: "German Dog"),
Dog(breed: "Bulldog Dog"),
Dog(breed: "Beagle Dog"),
Monkey(specie: "Capuchin Monkey"),
Monkey(specie: "Maqaques Monkey"),
Monkey(specie: "Cebidae Monkey"),
Giraffe(classification: "Northern Giraffe"),
Giraffe(classification: "Reticulated Giraffe"),
Giraffe(classification: "Masai Giraffe"),
Crocodile(classifications: "SaltWater Crocodile"),
Crocodile(classifications: "American Crocodile"),
Crocodile(classifications: "Nile Crocodile")
]

//calculate and display the number of each variation
let reptiles = array.filter { $0 is Crocodile }
let quadrupeds = array.filter { $0 is Dog || $0 is Monkey || $0 is Giraffe || $0 is Crocodile }
let animals = array.filter { $0 is Dog || $0 is Monkey || $0 is Giraffe || $0 is Crocodile }
let livingBeings = array.filter { $0 is Human || $0 is Dog || $0 is Monkey || $0 is Giraffe || $0 is Crocodile }

print("Number of reptiles: \(reptiles.count)")
print("Number of quadrupeds: \(quadrupeds.count)")
print("Number of animals: \(animals.count)")
print("Number of living beings: \(livingBeings.count)")

iacobzanoci
Автор

"То есть не к вашим родителям, а к родителям класса" :D

goalkingdom
Автор

//Lesson 18 Inheritance

//Task - 1
// - Create a base class artist with "firstname" and "lastname" and method "perfomance".
// - Each subclass "perfomance" method has own realization (actor: plays, dancer: dance, clown), make print.
// - Subclass "artist" wants to set name by itself
// - Put all instances in one array and walk through it calling "perfomance" method for all artist. When method is calling, to make a print with itself and firstname and lastname of the artist.

class Artist {

var firstName: String
var lastName: String

init(fisrtName: String, lastName: String) {
self.firstName = fisrtName
self.lastName = lastName
}

func perfomance() -> String {
return firstName + " " + lastName + " "
}
}

class Actor: Artist {
override func perfomance() -> String {
return super.perfomance() + "played in the best mode, his role in the movie!"
}
}

class Dancer: Artist {
override func perfomance() -> String {
return super.perfomance() + "showed a dance concert for the audience!"
}
}

class Clown: Artist {
override func perfomance() -> String {
return super.perfomance() + "made people laugh from his perfomance!"
}
}

class Painter: Artist {

override init(fisrtName: String, lastName: String) {
super.init(fisrtName: fisrtName, lastName: lastName)
self.firstName = "Mr. " + firstName
}

override func perfomance() -> String {
return super.perfomance() + "made his work to be famous for entire word!"
}
}

var actor = Actor(fisrtName: "Robrt", lastName: "Downie")
var dancer = Dancer(fisrtName: "Michelle", lastName: "Rodriguez")
var clown = Clown(fisrtName: "Dibi", lastName: "Dubi")
var painter = Painter(fisrtName: "Garry", lastName: "Chpoker")

func displayArtist() {

var artistArray = [actor, dancer, clown, painter]

for artist in artistArray {
print(artist.perfomance())
}
}

displayArtist()

iacobzanoci
Автор

11 комментариев? Серьезно? Давайте навалим движка

akhmedovbakhtovar
Автор

1)
class Artist {
var firstName: String
var surName: String
init(firstName: String, surname: String) {
self.firstName = firstName.capitalized
self.surName = surname.capitalized
}
func Show() -> String {
return "\(firstName) \(surName) Show:"
}
}

class Actor: Artist {
override func Show() -> String {
return super.Show() + " actor's game"
}
}

class Dancer: Artist {
override func Show() -> String {
return super.Show() + " tik tok"
}
}

class MusicianPlayer: Artist {
override func Show() -> String {
return super.Show() + " singing perfomance"
}
}

class Painter: Artist {
override var firstName: String {
get {
return + " - Z"
}
set {
super.firstName = newValue
}
}
override func Show() -> String {
return super.Show() + " drawing a picture"
}
}

let arrayArtist = [Dancer(firstName: "Nurs", surname: "Ryspanbetov"), Actor(firstName: "Ernur", surname: "Balmashev"), Painter(firstName: "aiDaR", surname: "Ospanov"), MusicianPlayer(firstName: "Almash", surname: "Ospanova") ]

for artist in arrayArtist {
print(artist.Show())
}


где Painter (можно сделать так super.firstName.count > 2 ?
- 2).uppercased().reversed()) + " - Z" : )
потому что, если напишите имя меньше трех, то будет ошибка и программа не будет работать

aidarospanov